Extract and Save Json to Arraylist Android - android

How can i extract the json below and save it in an arraylist.
{
"trains": {
"train": [
{
"#id": 1000000103,
"#version": 1,
"#status": "active",
"#name": "dffffff",
"#description": "ffffff half of the nineteenth century.",
"#city": "fff",
"#phone": "+230 595-1454",
"#email": "ffffr#mffc.mu",
"#website": "www4u",
"#latitude": -5.2882,
"#longitude": 3.499,
"#defaultLocale": "",
"#holes": 48,
"#par": 72,
"#slope": 0,
"#distance": 5.005273,
"circuits": {
"circuit": []
},
"localizations": {
"localization": []
}
},
{
"#id": 1000000105,
"#version": 1,
"#status": "active",
"#name": " xClub",
"#description": "",
"#city": " xlet",
"#phone": "+44465\t",
"#email": "",
"#website": "wweffl.com",
"#latitude": -2.040318,
"#longitude": 54548,
"#defaultLocale": "",
"#holes": 18,
"#par": 32,
"#slope": 0,
"#distance": 2441673,
"circuits": {
"circuit": []
},
"localizations": {
"localization": []
}
}
]
}
}
my working
try {
jobj_trouve_train = new JSONObject(reponse_trouve_train);
String jsonobj = jobj_trouve_golf.getString("trains");
//String jsonobj1 = jobj_trouve_golf.getString("train");
//jobj_trouve_train = new JSONObject(reponse_trouve_train);
//jsonArray = jobj_trouve_golf.getJSONArray("trains");
//jsonArray= new JSONArray(jsonobj);
//System.out.println("jsonArray "+jsonArray);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Try this..
try {
jobj_trouve_train = new JSONObject(reponse_trouve_train);
JSONObject jsonobj = jobj_trouve_train.getJSONObject("trains");
JSONArray jsonobj1 = jsonobj.getJSONArray("train");
for(int i = 0;i< jsonobj1.length();i++){
JSONObject jsonj = jsonobj1.getJSONObject(i);
System.out.println("#id "+jsonj.getString("#id"));
// Same for remaining all
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

You can use the Gson library developed by Google to parse Json into objects.
The reference is here:
https://code.google.com/p/google-gson/
And, a sample example is here:
JSON Parsing with GSON

JSONObject trains = jobj_trouve_train.getJSONObject("trains");
JSONArray trainArray = trains.getJSONArray("train");
JSONObject train1 = trainArray.getJSONObject(0);
...
if i didn't get confuse maybe this one will be right

JSONArray jasonArray = new JSONArray(result.getProperty("trains").toString());
for (int i = 0; i < jasonArray.length(); i++) {
JSONObject jsonObj = jasonArray.optJSONObject(i);
trainObject = new JSONObject(jsonObj.optString("train").toString());
int id = trainObject.optInt("id");
and so on..
}

public Object void toObject(String jsonMsg) throws JSONException {
JSONObject trains= (JSONObject) new JSONTokener(jsonMsg).nextValue();
if(trains.has("trains")){
JSONArray train = (JSONArray) new JSONTokener(object.getString("train")).nextValue();
for (int t = 0; t < jsonArray.length(); t++) {
String temp = jsonArray.getJSONObject(t).toString();
JSONObject object = (JSONObject) new JSONTokener(temp).nextValue();
if(object.has("#id"))
object.getString("#id");
// now similar procedure of reading
// read values and save it in an "object"
}
return savedObject;
}
-- tested, i have tried to modify code to match your JSON data. complete the rest.

Related

How to get json object and array values?

How to parse JSON values in this format? I want to get the details of the data element but inside data there are 'dates' and inside dates there is array containing two more elements. I want to get all the dates first inside data and then within these dates I want all the information within these dates. How can I achieve this? Please Help. I tried with below code but it hasn't worked
try {
JSONObject jsonObject = new JSONObject("data");
JSONArray jsonArray =jsonObject.getJSONArray(String.valueof(cuurentdate));
JSONArray session;
for (int i = 0; i < jsonArray.length() - 1; i++) {
jsonObject = jsonArray.getJSONObject(i);
session= jsonObject.getJSONArray("session");
Log.d("MyLog", session + "");
}
} catch (JSONException e) {
e.printStackTrace();
}
Following is the format
{
"status": 1,
"status_code": 200,
"data": {
"2018-02-11": [
{
"session": "01:00 AM",
"place": true
},
{
"session": "02:00 AM",
"place": true
}
],
"2018-02-12": [
{
"session": "01:00 AM",
"place": true
},
{
"session": "02:00 AM",
"place": true
}
]
}
}
You just need to pass the response string to the method. You can try this:
private void jsonParsing(String jsonString) {
// String jsonString = "{ \"status\": 1, \"status_code\": 200, \"data\": { \"2018-02-11\": [ { \"session\": \"01:00 AM\", \"place\": true }, { \"session\": \"02:00 AM\", \"place\": true } ], \"2018-02-12\": [ { \"session\": \"01:00 AM\", \"place\": true }, { \"session\": \"02:00 AM\", \"place\": true } ] } }";
try {
JSONObject jsonObject = new JSONObject(jsonString);
JSONObject dataObj = jsonObject.getJSONObject("data");
Iterator<String> iter = dataObj.keys();
Log.e(TAG, "jsonParsing: "+iter );
while (iter.hasNext()) {
String key = iter.next();
JSONArray datesArray = dataObj.getJSONArray(key);
ArrayList<String> sessions = new ArrayList<String>();
for (int i = 0; i < datesArray.length(); i++) {
JSONObject datesObject = datesArray.getJSONObject(i);
sessions.add(datesObject.getString("session"));
}
Log.d("MyLog", sessions + "");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
(1) get JSONObject of Main json
JSONObject objMain = new JSONObject("your json string");
(2)get JSONObject of "data" from main json
JSONObject jsonData = objMain.getJSONObject("data")
(3) get all keys (dates) from object "data"
Iterator<String> iter = jsonData.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
JSONArray arrayDate = objData.getJSONArray(key)
for (i = 0; i < arrayDate.length(); i++) {
JSONObject objDate = arrayDate.getJSONObject(i)
Log.d("#session :", "" + objDate.getString("session"))
Log.d("#place :", "" + objDate.getBoolean("place"))
}
} catch (JSONException e) {
// Something went wrong!
}
}
try this one code
IN THIS CODE jsonMstObject IS TEMP OBJECT YOU HAVE TO USE YOUR API RESPONSE JSONobject INSTEAD OF jsonMstObject
try {
JSONObject jsonMstObject = new JSONObject("{"status":1,"status_code":200,"data":{"2018-02-11":[{"session":"01:00 AM","place":true},{"session":"02:00 AM","place":true}],"2018-02-12":[{"session":"01:00 AM","place":true},{"session":"02:00 AM","place":true}]}}");
JSONObject jsonObject = jsonMstObject.getJSONObject("data");
JSONArray jsonArray =jsonObject.getJSONArray(String.valueof(cuurentdate));
ArrayList<String> arrSession = new ArrayList<String>();
for (int i = 0; i < jsonArray.length(); i++) {
jsonObject = jsonArray.getJSONObject(i);
arrSession.add(jsonObject.getString("session"));
}
Log.d("MyLog", arrSession + "");
} catch (JSONException e) {
e.printStackTrace();
}
in this code arrSession is your session string array
Ex. you passed cuurentdate = "2018-02-11" then you recived result like
[01:00 AM, 02:00 AM]
Note: this code is worked based on your cuurentdate param. This is code for get static date array from data and create String Array.

Unable to parse JsonArray inside JsonArray

Hi i was trying to parse a json array inside another json array. Help me with this.
my Json Array is
"results":[
{
"percentcompleted":0,
"requirers":[
{
"activityContext":null,
"auditReason":null,
"assignee":{
"sourceType":"InternalPerson",
"activitySourceType":{
"listId":"sysli000000000003037",
"sourceType":0,
"key":"0",
"displayName":"Person"
},
"locale":{
"id":"local000000000000001",
"displayName":"English"
},
"id":"emplo000000006156648",
"displayName":"Venkat Rao"
},
"targetDate":null,
"assignment":{
"id":"stcur000000000003182",
"displayName":null
},
"learningEvent":{
"id":"curra000000000003001",
"displayName":"Studieplan_test för OKQ8"
},
"jobTypeId":null,
"listIds":null,
"assignedOn":1502084325000,
"source":{
"sourceType":"InternalPerson",
"activitySourceType":{
"listId":"sysli000000000003037",
"sourceType":0,
"key":"0",
"displayName":"Person"
},
"locale":{
"id":"local000000000000001",
"displayName":"English"
},
"id":"emplo000000006156648",
"displayName":"Venkat Rao"
},
"required":true,
"actions":null,
"id":"currh000000000014343"
}
],
"basicdetail":{
"revokedOn":null,
"need_recert":false,
"curriculum":{
"id":"curra000000000003001",
"displayName":"Studieplan_test för OKQ8"
},
"recert_window_starts_on":null,
"createdBy":"vrao",
"updatedBy":"vrao",
"createdOn":1502084325000,
"updatedOn":1508357353000,
"status":{
"intStatus":400,
"description":"Assigned",
"displayName":"Assigned"
},
"type":"CURRICULUM",
"path":{
"id":"track000000000003081",
"displayName":"Studieplan"
},
"acquiredOn":null,
"assignee":{
"sourceType":"InternalPerson",
"activitySourceType":{
"listId":"sysli000000000003037",
"sourceType":0,
"key":"0",
"displayName":"Person"
},
"locale":{
"id":"local000000000000001",
"displayName":"English"
},
"id":"emplo000000006156648",
"displayName":"Venkat Rao"
},
"targetDate":null,
"startedOn":null,
"assignedOnDate":1502084325000,
"heldCertNo":"00003787",
"owner":{
"sourceType":"InternalPerson",
"activitySourceType":{
"listId":"sysli000000000003037",
"sourceType":0,
"key":"0",
"displayName":"Person"
},
"locale":{
"id":"local000000000000001",
"displayName":"English"
},
"id":"emplo000000006156648",
"displayName":"Venkat Rao"
},
"id":"stcur000000000003182",
"assigneeAdditionalDetails":{
"person_no":"VRAO",
"username":"VRAO"
}
},
"isgranted":null
},
and my Code to parse the above data is
public class CurriculaParser {
public ArrayList<CurriculaData> getData(String response)
{
ArrayList<CurriculaData> dataList = new ArrayList<>();
try {
JSONObject mainObj = new JSONObject(response);
JSONArray array = mainObj.getJSONArray("results");
CurriculaData data;
for(int i = 0;i<array.length();i++)
{
data = new CurriculaData();
JSONObject resObj = array.getJSONObject(i);
JSONArray reqArray = resObj.getJSONArray("requires");
for( int j =0;j<reqArray.length();j++) {
JSONObject reqObj = reqArray.getJSONObject(j);
JSONObject innerObj = reqObj.getJSONObject("learningEvent");
data.setTitle(innerObj.getString("displayName"));
data.setAssignedOn(reqObj.getString("assignedOn"));
}
JSONArray basicDetailArray = resObj.getJSONArray("basicdetail");
for(int k=0;k<basicDetailArray.length();k++) {
JSONObject basicDetailObj = basicDetailArray.getJSONObject(k);
JSONObject statusObj = basicDetailObj.getJSONObject("status");
data.setStatus(statusObj.getString("displayName"));
data.setAcquiredOn(basicDetailObj.getString("acquiredOn"));
JSONObject assignObj = basicDetailObj.getJSONObject("assignee");
data.setAssignedBy(assignObj.getString("displayName"));
}
dataList.add(data);
}
} catch (Exception e) {
e.printStackTrace();
}
return dataList;
}
and finally i got error like
org.json.JSONException: No value for requires
let me know the error what i made and iam a beginner in dealing with jsonarray inside another jsonarray
org.json.JSONException: No value for requires
JSONException
KEY mismatches on lookups
You should pass requirers instead of requires.
JSONArray reqArray = resObj.getJSONArray("requirers");
fixed the requires TYPO error
public class CurriculaParser {
public ArrayList<CurriculaData> getData(String response)
{
ArrayList<CurriculaData> dataList = new ArrayList<>();
try {
JSONObject mainObj = new JSONObject(response);
JSONArray array = mainObj.getJSONArray("results");
CurriculaData data;
for(int i = 0;i<array.length();i++)
{
data = new CurriculaData();
JSONObject resObj = array.getJSONObject(i);
JSONArray reqArray = resObj.getJSONArray("requirers");
for( int j =0;j<reqArray.length();j++) {
JSONObject reqObj = reqArray.getJSONObject(j);
JSONObject innerObj = reqObj.getJSONObject("learningEvent");
data.setTitle(innerObj.getString("displayName"));
data.setAssignedOn(reqObj.getString("assignedOn"));
}
JSONArray basicDetailArray = resObj.getJSONArray("basicdetail");
for(int k=0;k<basicDetailArray.length();k++) {
JSONObject basicDetailObj = basicDetailArray.getJSONObject(k);
JSONObject statusObj = basicDetailObj.getJSONObject("status");
data.setStatus(statusObj.getString("displayName"));
data.setAcquiredOn(basicDetailObj.getString("acquiredOn"));
JSONObject assignObj = basicDetailObj.getJSONObject("assignee");
data.setAssignedBy(assignObj.getString("displayName"));
}
dataList.add(data);
}
} catch (Exception e) {
e.printStackTrace();
}

Android : How to access a JSONObject

I'm new to Android and I have tried so many options to access the JSONObject which returns from an API call but I couldn't succeed as any of the solutions i looked for didn't work for me.
What i want is to access the JSONObject and keep the Id & Name in a Array. And then populate the Names in a AutoCompleteTextView. How do i properly access the JSONObject. Please help me with this. I'm stuck on this for more than a day.
Following is my Code handling the JSONObject.
#Override
public void processFinish(JSONObject output) {
Toast.makeText(MainActivity.this,"ProcessFinish",Toast.LENGTH_SHORT).show();
allStations = output;
if(output != null){
Toast.makeText(MainActivity.this,output.toString(),Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(MainActivity.this," Connection Failed!",Toast.LENGTH_SHORT).show();
}
}
Following is a sample output of my JSONObject
{
"SUCCESS": true,
"MESSAGE": "Found 398 Results!",
"NOFRESULTS": 3,
"RESULTS": {
"stationList": [
{
"stationCode": "ABN",
"stationID": 3,
"stationName": "ABLA"
},
{
"stationCode": "ADLA",
"stationID": 410,
"stationName": "ADLA"
},
{
"stationCode": "ANM",
"stationID": 11,
"stationName": "AHAMA"
}]
},
"STATUSCODE": "2000"
}
try this
try {
JSONObject obj= output.getJSONObject("RESULTS");
JSONArray dataArray= obj.getJSONArray(“stationList“);
for(int i=0;i<dataArray.length();i++)
{
JSONObject object1=dataArray.getJSONObject(i);
Strind id = object1.getString("stationID");
}
} catch (JSONException e) {
e.printStackTrace();
}
In This code output is your JSONObject result
try this
try {
JSONObject jsonObject = new JSONObject("response");
boolean status= jsonObject.getBoolean("SUCCESS");
String MESSAGE= jsonObject.getString("MESSAGE");
String NOFRESULTS= jsonObject.getString("NOFRESULTS");
String STATUSCODE= jsonObject.getString("STATUSCODE");
JSONObject obj=jsonObject.getJSONObject("RESULTS");
JSONArray jsonarray = obj.optJSONArray("stationList");
for (int i = 0; i < jsonarray.length(); i++){
JSONObject json_data = jsonarray.getJSONObject(i);
Log.e("stationCode",json_data.getString("stationCode"));
Log.e("stationID",json_data.getString("stationID"));
Log.e("stationName",json_data.getString("stationName"));
}
} catch (JSONException e) {
e.printStackTrace();
}
Have you tried using a JSON Array? For example you could use this method for storage:
JSONObject wgroup = new JSONObject(); //FINAL json object
try { //put initial data
wgroup.put("id", "2");
wgroup.put("user", "someone");
wgroup.put("stime", "2017-02-06 16:30:13");
wgroup.put("etime", "2017-02-06 19:30:13");
wgroup.put("real_dur", 3600);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONArray jsonArray1 = new JSONArray(); //Create an array to store ALL Variables
for (int y=0; y< your_array.length ; y++ ){ //loop through your information array
JSONObject output = new JSONObject(); //CREATE a json object to put 1 workout
try {
wgroup.put("id", "2");
wgroup.put("name", "sam");
wgroup.put("age", "3");
wgroup.put("gender", "male");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONArray jsonArray2 = new JSONArray(); //CREATE a json array to put 1 array
jsonArray1.put(output); //insert this OBJECT into the ARRAY
}
wgroup.put(jsonArray1);//insert the workouts ARRAY into the original object

nested JSON object inside JSON array

I'm trying to parse a JSON object. The JSON response is as follows.
{
"message": "Success",
"list": [
{
"orderId": 24,
"phoneNumber": "1234567893",
"totalAmount": 100,
"addressBean": {
"cadId": 1,
"phone2": "1234567899",
"address1": "34, gandhi nagar",
}
},
Android code which i have tried for getting "orderId", "phoneNumber" and "totalAmount" is below.
final List<OrderModel> orderList = new ArrayList<>();
public void onResponse(JSONObject response) {
try {
if (response.getString("message").equalsIgnoreCase("Success")) {
JSONArray jArray = response.getJSONArray("list");
for (int i = 0; i < jArray.length(); i++) {
OrderModel model = new OrderModel();
orderModel.setOrderId(jArray.getJSONObject(i).getString("orderId"));
orderModel.setphoneNumber(jArray.getJSONObject(i).getString("phoneNumber"));
orderModel.setTotalAmount(new BigDecimal(jArray.getJSONObject(i).getString("totalAmount")));
orderList.add(orderModel);
}
setOrderList(orderList);
I want to show the "cadId", "phone2" and "address1" in a Textview. How can i do that?
Try to use this Code
try {
JSONArray jArray = response.getJSONArray("list");
for (int i = 0; i < jArray.length(); i++) {
JSONObject jsonObject = jArray.getJSONObject(i);
if (jsonObject.has("addressBean")){
JSONObject addressObject = jsonObject.getJSONObject("addressBean");
int cadId = addressObject.getInt("cadId");
String phone = addressObject.getString("phone2");
String address = addressObject.getString("address1");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
Code for phone2
String phone2 = jArray.getJSONObject(i).getJSONObject("addressBean").getString("phone2");
Use getInt() for cadId

Android how to loop through this json?

How can I loop through this kind of JSON array?
[
{
"full_name": "Abc Xyz"
},
{
"full_name": "Def Xyz"
},
{
"full_name": "Nml Xyz"
},
{
"full_name": "Jol Xyz"
}
]
Thank you!
try this
try {
JSONArray a = new JSONArray(myjsonString);
for(int i = 0; i < a.length(); i++)
{
JSONObject o = a.getJSONObject(i);
String name = o.getString("full_name");
}
} catch (JSONException e) {
e.printStackTrace();
}
Your jsonString contains array of objects so here is code:
try {
// [] indicates array so top element is array
JSONArray jsonArray = new JSONArray(jsonString);
for(int i = 0; i < jsonArray.length(); i++)
{
// {} indicates object so array elements are objects
JSONObject jsonObject = jsonArray.getJSONObject(i);
String name = jsonObject.getString("full_name");
}
} catch (JSONException e) {
e.printStackTrace();
}
Updated : Google GSON
Also try Google's GSON this is excellent library to handle jsons you can serialize and deserialize the json and class objects.
checkout this link: Google Gson
Try
try {
JSONArray array = new JSONArray(jsonString);
for(int i = 0; i < array.length(); i++) {
JSONObject json = array.getJSONObject(i);
String fullName = json.getString("full_name");
}
} catch (JSONException e) {
e.printStackTrace();
}

Categories

Resources