Check JSON Value which comes dynamically from the Server - android

I have JSON Response like this.I have tried a lot but unable to parse the Values.
{
"ResponseCode": "000",
"ResponseDescription": "Successful",
"SystemServiceID": [
"4"
],
"SystemServiceName": [
"Test Name"
],
"ProductID": [
"10"
],
"ProductName": [
"Testing"
],
"ProductDescription": [
"Test product"
],
"MinimumValue": [
10000
],
"MaximumValue": [
500000
],
"ImageURL": [
null
],
"Country": [
"Test"
],
"CompanyID": [
"1"
],
"CompanyName": [
"Test"
],
"FieldLevel": [
"2"
],
"FieldInfo": [
"{\"Field1\":{\"Field Name\":\"Phone Number\",\"Field Type\":\"Number\",\"Validation\":{\"Min\":\"4\",\"Max\":\"8\"}},\"Field2\":{\"Field Name\":\"Email\",\"Field Type\":\"String\",\"Validation\":{\"Regular Expression\":\"aaaaa\",\"Min Length\":\"10\",\"Max Length\":\"20\"}}}"
]
}
I have the last field FieldInfo which have the Field1,Field2 which comes dynamically from the server means sometimes FieldInfo have 2 Fields or Sometimes 3 Fields or Sometimes it have 4 fields and so on.
If it have the 2 Fields then it should be Field1,Field2
If it have the 3 Fields then it should be Field1,Field2,Field3 and so on.
Code
private ArrayList<BillPayProduct> parseBillPayResult(String data)
{
try
{
final JSONObject jsonObject=new JSONObject(data);
JSONArray jsonArray;
if(jsonObject.getString("ResponseCode").equals("000"))/*&&jsonObject.getString("ResponseDescription").equals("Successful"))*/
{
sysSerID=new ArrayList<String>();
sysSerName=new ArrayList<String>();
productID=new ArrayList<String>();
productName=new ArrayList<String>();
productDesc=new ArrayList<String>();
minVal=new ArrayList<String>();
maxVal=new ArrayList<String>();
ImageURL=new ArrayList<String>();
Country=new ArrayList<String>();
CompanyID=new ArrayList<String>();
CompanyName=new ArrayList<String>();
FieldLevel=new ArrayList<String>();
FieldInfo=new ArrayList<String>();
if(jsonObject.has("SystemServiceID"))
{
jsonArray=jsonObject.getJSONArray("SystemServiceID");
System.out.println("Length of systemserviceID:"+jsonArray.length()+"\ngetting System ServiceID");
for(int i=0;i<jsonArray.length();i++)
{
sysSerID.add(jsonArray.getString(i));
}
}
if(jsonObject.has("SystemServiceName"))
{
jsonArray=jsonObject.getJSONArray("SystemServiceName");
System.out.println("Length of SystemServiceName:"+jsonArray.length()+"\ngetting System ServiceName");
for(int i=0;i<jsonArray.length();i++)
{
sysSerName.add(jsonArray.getString(i));
}
}
if(jsonObject.has("ProductID"))
{
jsonArray=jsonObject.getJSONArray("ProductID");
System.out.println("Length of ProductID:"+jsonArray.length()+"\ngetting ProductID");
for(int i=0;i<jsonArray.length();i++)
{
productID.add(jsonArray.getString(i));
}
}
if(jsonObject.has("ProductDescription"))
{
jsonArray=jsonObject.getJSONArray("ProductDescription");
System.out.println("Length of ProductDescription:"+jsonArray.length()+"\ngetting ProductDescription");
for(int i=0;i<jsonArray.length();i++)
{
productDesc.add(jsonArray.getString(i));
}
}
if(jsonObject.has("BatchID"))
{
jsonArray = jsonObject.getJSONArray("BatchID");
System.out.println("length of BatchID:"+jsonArray.length()+"\nGetting BatchID");
for(int i=0;i<jsonArray.length();i++)
{
batchID.add(jsonArray.getString(i));
}
}
if(jsonObject.has("MinimumValue"))
{
jsonArray = jsonObject.getJSONArray("MinimumValue");
System.out.println("length of MinimumValue:"+jsonArray.length()+"\nGetting MinimumValue");
for(int i=0;i<jsonArray.length();i++)
{
minVal.add(jsonArray.getString(i));
}
}
if(jsonObject.has("MaximumValue"))
{
jsonArray = jsonObject.getJSONArray("MaximumValue");
for(int i=0;i<jsonArray.length();i++)
{
maxVal.add(jsonArray.getString(i));
System.out.println(jsonArray.getString(i));
}
}
if(jsonObject.has("ProductName"))
{
jsonArray=jsonObject.getJSONArray("ProductName");
System.out.println("length of productID:"+jsonArray.length()+"\nGetting product name");
for(int i=0;i<jsonArray.length();i++)
{
productName.add(jsonArray.getString(i));
}
}
/*if(jsonObject.has("ProductType"))
{
jsonArray=jsonObject.getJSONArray("ProductType");
System.out.println("length of productID:"+jsonArray.length()+"\nGetting product Type");
for(int i=0;i<jsonArray.length();i++)
{
productType.add(jsonArray.getString(i));
}
}*/
if(jsonObject.has("ImageURL"))
{
jsonArray=jsonObject.getJSONArray("ImageURL");
System.out.println("length of ImageURL:"+jsonArray.length()+"\nGetting ImageURL");
for(int i=0;i<jsonArray.length();i++)
{
ImageURL.add(jsonArray.getString(i));
}
}
if(jsonObject.has("Country"))
{
jsonArray=jsonObject.getJSONArray("Country");
System.out.println("length of ImageURL:"+jsonArray.length()+"\nGetting Country");
for(int i=0;i<jsonArray.length();i++)
{
Country.add(jsonArray.getString(i));
}
}
if(jsonObject.has("CompanyID"))
{
jsonArray=jsonObject.getJSONArray("CompanyID");
System.out.println("length of CompanyID:"+jsonArray.length()+"\nGetting CompanyID");
for(int i=0;i<jsonArray.length();i++)
{
CompanyID.add(jsonArray.getString(i));
}
}
if(jsonObject.has("CompanyName"))
{
jsonArray=jsonObject.getJSONArray("CompanyName");
System.out.println("length of CompanyName:"+jsonArray.length()+"\nGetting CompanyName");
for(int i=0;i<jsonArray.length();i++)
{
CompanyName.add(jsonArray.getString(i));
}
}
if(jsonObject.has("FieldLevel"))
{
jsonArray=jsonObject.getJSONArray("FieldLevel");
System.out.println("length of FieldLevel:"+jsonArray.length()+"\nGetting FieldLevel");
for(int i=0;i<jsonArray.length();i++)
{
FieldLevel.add(jsonArray.getString(i));
}
}
if(jsonObject.has("FieldInfo"))
{
jsonArray=jsonObject.getJSONArray("FieldInfo");
System.out.println("length of FieldInfo:"+jsonArray.length()+"\nGetting FieldInfo");
for(int i=0;i<jsonArray.length();i++)
{
FieldInfo.add(jsonArray.getString(i));
}
}
ArrayList<BillPayProduct> BillPayproductList=new ArrayList<BillPayProduct>();
for(int i=0;i<productID.size();i++)
{
BillPayProduct billpay_products=new BillPayProduct();
billpay_products.setSystemServiceID((String)sysSerID.get(i));
billpay_products.setSystemServiceName((String)sysSerName.get(i));
billpay_products.setProductID((String)productID.get(i));
billpay_products.setProductName((String)productName.get(i));
billpay_products.setProductDesc((String)productDesc.get(i));
billpay_products.setMinValue((String)minVal.get(i));
billpay_products.setMaxValue((String)maxVal.get(i));
billpay_products.setImageURL((String)ImageURL.get(i));
billpay_products.setCountry((String)Country.get(i));
billpay_products.setCompanyID((String)CompanyID.get(i));
billpay_products.setCompanyName((String)CompanyName.get(i));
billpay_products.setFieldLevel((String)FieldLevel.get(i));
billpay_products.setFieldInfo((String)FieldInfo.get(i));
//inserting product into Database.
//inserting product into ArrayList
BillPayproductList.add(billpay_products);
}
return BillPayproductList;
}
}
catch (final JSONException e)
{
return null;
}
}
Bean Class
public class BillPayProduct extends Products
{
String Country;
String CompanyID;
String CompanyName;
String FieldLevel;
String FieldInfo;
public String getCountry()
{
return Country;
}
public void setCountry(String country)
{
Country = country;
}
public String getCompanyID()
{
return CompanyID;
}
public void setCompanyID(String companyID)
{
CompanyID = companyID;
}
public String getCompanyName()
{
return CompanyName;
}
public void setCompanyName(String companyName)
{
CompanyName = companyName;
}
public String getFieldLevel()
{
return FieldLevel;
}
public void setFieldLevel(String fieldLevel)
{
FieldLevel = fieldLevel;
}
public String getFieldInfo()
{
return FieldInfo;
}
public void setFieldInfo(String fieldInfo)
{
FieldInfo = fieldInfo;
}
}
My Question is that how can i check that how many fields it have???
And how to parse it and stored ?
What is the most preferable way to store the those values?
Any Help will be appreciated.
Thanks in Advance ... :)

you can enumerate the keys of the root, for instance
Iterator<String> keys = obj.keys();
What is the most preferable way to store the those values?
Tipically I create a read-only class, with the values I expect and I add it to a collection:
public class JSONDescriptor {
public final String filed1;
public final String filed2;
public JSONDescriptor(String filed1, String filed2) {
this.field1 = field1;
this.field2 = field2;
}
}

JSONObject jsonObject = new JSONObject(JSONResponse);
String mResponseCode = jsonObject.getString("ResponseCode");
String mResponseDescription = jsonObject.getString("ResponseDescription");
JSONArray jsonArray = jsonObject.getJSONArray("SystemServiceID");
Within this jsonArray you have only one value.If it's like that we can't able to parse the value.
So,it should be like this format"Id": "4"(which means object and it's value) within jsonArray.
Otherwise, if it takes only one id then change it to "SystemServiceID": "4"this format and it can be parsed as mRsespoonseCode parsing technique.
thanks dude. If you have any queries pls add comment.

Here is the exactly way to parse your JSON String :
JSONObject mMainObj = new JSONObject(mMyResult);
if(mMainObj != null){
String response = mMainObj.getString("ResponseCode"); // gets ResponseCode
String desc = mMainObj.getString("ResponseDescription"); //gets ResponseDescription
// SystemServiceID
JSONArray mSysService = mMainObj.getJSONArray("SystemServiceID");
if(mSysService != null){
for (int j = 0; j < mSysService.length(); j++) {
int mId = mSysService.getInt(j); // gets 4 and all other values, if there are some
}
}
// SystemServiceName
JSONArray mSysServiceName = mMainObj.getJSONArray("SystemServiceName");
if(mSysServiceName != null){
for (int j = 0; j < mSysServiceName.length(); j++) {
String mName = mSysServiceName.getString(j); // gets Test Name and all other values, if there are some
}
}
// The same for ProductID, ProductName and etc.
JSONArray mFieldInfo = mMainObj.getJSONArray("FieldInfo");
if(mFieldInfo != null){
for(int j = 0; j < mFieldInfo.length(); j++){
JSONObject mItem = mFieldInfo.getJSONObject(i);
if(mItem != null){
Iterator<Object> keys = mItem.keys();
while(keys.hasNext()){
String id = String.valueOf(keys.next()); // This value represent Field1
JSONArray mField = mItem.getJSONArray(id);
if(mField != null){
for(int i = 0; i < mField.length();i++){
JSONObject mElem = mField.getJSONObject(i);
if(mElem != null){
String mFieldName = mElem.getString("Field Name"); // value: Phone Number
// and etc.
}
}
}
}
}
}
}
}
Didn't tested the code, there can be some typo mistakes, if it's not working correctly just post a comment and I will fix it.
Hope this helps! : )

Related

How to properly parse a Firestore API JSON?

I'm using Google Cloud Firestore API for a project that involves simple retrieval of data from the server database. Having set up everything I can't seem to figure out how to properly parse the returned JSON, as all of my attempts have been unsuccessful.
Using the Firestore package is out of question as this is a defined project.
I have tried the classic approach since Android studio only gets the field part with its HTTPURLConnection.
This is the JSON structure:
{
"documents": [
{
"name": "projects/...",
"fields": {
"name": {
"stringValue": "Q1"
},
"myValues": {
"arrayValue": {
"values": [
{
"stringValue": "First"
}
]
}
},
"index": {
"integerValue": "0"
}
},
"createTime": "2019-05-24T10:07:10.864421Z",
"updateTime": "2019-05-28T07:52:34.445600Z"
}
]
}
Here's my attempt at parsing it:
public ArrayList<Question> parse(String json)
{
ArrayList<Question> list = new ArrayList<Question>();
try {
int indeks=0;
String qName="";
ArrayList<String> answerList= new ArrayList<String>();
JSONObject object = new JSONObject(json);
JSONArray dokumenti = object.getJSONArray("documents");
for (int j = 0; j < dokumenti.length(); j++) {
JSONObject jObject = dokumenti.getJSONObject(j);
if (jObject.has("index")) indeks = jObject.getInt("index");
if (jObject.has("name")) qName= jObject.getString("name");
JSONArray answerArray= jObject.getJSONArray("myValues");
for (int i = 0; i < answerArray.length(); i++) {
try {
String answer= answerArray.getString(i);
answerList.add(answer);
} catch (JSONException e) {
Log.d("OOPS", qName);
}
}
}
list.add(new Question(qName, qName, answerList, answerList.get(indeks), 0));
}
catch(JSONException e)
{
//something
}
return list;
}
Database structure
I expect that all of the documents get parsed and added to the list ArrayList but it seems like nothing happens and I can't find the TAG in the Logcat.
It looks you're trying to get index before accessing its parent fields.
if (jObject.has("index")) indeks = jObject.getInt("index");
In this line you should have gotten before the parent object fields, otherwise you will not have access to index or name.
EDIT
I've been checking your code and you are parsing some things wrong.
Let's go step by step:
You are trying to access to the childs of fields without accessing to their parent.
The solution following your structure would be something like this:
JSONObject jObject = dokumenti.getJSONObject(j);
JSONObject fields = jObject.getJSONObject("fields");
if (fields.has("index") && fields.getJSONObject("index").has("integerValue")) {
indeks = fields.getJSONObject("index").getInt("integerValue");
}
if (fields.has("name") && fields.getJSONObject("name").has("stringValue")) {
qName = fields.getJSONObject("name").getString("stringValue");
}
You're trying to access also the myValues array not respecting the objects hierarchy. The correct way should be something like this:
JSONArray answerArray = fields.getJSONObject("myValues").getJSONObject("arrayValue").getJSONArray("values");
for (int i = 0; i < answerArray.length(); i++) {
try {
String answer = answerArray.getJSONObject(i).getString("stringValue");
answerList.add(answer);
} catch (JSONException e) {
Log.d("OOPS", qName);
}
}
With this changes I have been able to parse the Json you posted without any problem. Here you can find the complete code:
public ArrayList<Question> parse(String json)
{
ArrayList<Question> list = new ArrayList<Question>();
try {
int indeks = 0;
String qName = "";
ArrayList<String> answerList = new ArrayList<String>();
JSONObject object = new JSONObject(json);
JSONArray dokumenti = object.getJSONArray("documents");
for (int j = 0; j < dokumenti.length(); j++) {
JSONObject jObject = dokumenti.getJSONObject(j);
JSONObject fields = jObject.getJSONObject("fields");
if (fields.has("index") && fields.getJSONObject("index").has("integerValue")) {
indeks = fields.getJSONObject("index").getInt("integerValue");
}
if (fields.has("name") && fields.getJSONObject("name").has("stringValue")) {
qName = fields.getJSONObject("name").getString("stringValue");
}
JSONArray answerArray = fields.getJSONObject("myValues").getJSONObject("arrayValue").getJSONArray("values");
for (int i = 0; i < answerArray.length(); i++) {
try {
String answer= answerArray.getString(i);
answerList.add(answer);
} catch (JSONException e) {
Log.d("OOPS", qName);
}
}
}
list.add(new Question(qName, qName, answerList, answerList.get(indeks), 0));
}
catch(JSONException e)
{
//something
}
return list;
}
JavaScript example:
function toValue(field) {
return "integerValue" in field
? Number(field.integerValue)
: "doubleValue" in field
? Number(field.doubleValue)
: "arrayValue" in field
? field.arrayValue.values.map(toValue)
: "mapValue" in field
? toJSON(field.mapValue)
: Object.entries(field)[0][1];
}
function toJSON(doc) {
return Object.fromEntries(
Object.entries(doc.fields ?? {}).map(([key, field]) => [key, toValue(field)])
);
}

just only one list on my listview

I have array look like this :
"results":[
{
"code":"jne",
"name":"Jalur Nugraha Ekakurir (JNE)",
"costs":[
{
"service":"OKE",
"description":"Ongkos Kirim Ekonomis",
"cost":[
{
"value":38000,
"etd":"4-5",
"note":""
}
]
},
{
"service":"REG",
"description":"Layanan Reguler",
"cost":[
{
"value":44000,
"etd":"2-3",
"note":""
}
]
},
{
"service":"SPS",
"description":"Super Speed",
"cost":[
{
"value":349000,
"etd":"",
"note":""
}
]
},
{
"service":"YES",
"description":"Yakin Esok Sampai",
"cost":[
{
"value":98000,
"etd":"1-1",
"note":""
}
]
}
]
}
]
My code on android to process array, problem in my code on function "for" before I copy and edit another code from file :
JSONObject jsonObjsko = new JSONObject(rajaongkir);
String resultse = jsonObjsko.getString("results");
JSONArray jsonObjssto = new JSONArray(resultse);
JSONObject mJsonObject = jsonObjssto.getJSONObject(0);
costs = mJsonObject.getString("costs");
JSONArray jsonArray = new JSONArray(costs);
for (int k = 0; k < jsonArray.length(); k++) {
try {
JSONArray jsonArrayp = new JSONArray(costs);
JSONObject jsonObject = jsonArrayp.getJSONObject(k);
String serviceq = jsonObject.getString("cost");
String servicel = jsonObject.getString("service");
kon = String.valueOf(jsonArray.length());
kin = kin + k;
JSONArray jsonObjsstorng = new JSONArray(serviceq);
JSONObject mJsonObjectrng = jsonObjsstorng.getJSONObject(k);
String values = mJsonObjectrng.getString("value");
ShipPerActiv wp = new ShipPerActiv(servicel, values);
arraylist.add(wp);
}
catch (JSONException e) {
e.printStackTrace();
}
}
This code for ShipPerActiv for add arraylist :
public class ShipPerActiv {
private String services;
private String hongkir;
public ShipPerActiv(String services,String hongkir) {
this.services = services;
this.hongkir = hongkir;
}
public String getservices() {return this.services; }
public String gethongkir() {return this.hongkir; }
}
I tried use harddebug with kon & kin true function for normal but not on my listview just one int(0) not int(1)~etc
At first convert your StringObject to JSONObject and dont forget to add { at first of string and } to end of string:
JSONObject parentObject = new JSONObject("{"+"JsonString"+"}");
Then parse your object like this :
try {
JSONObject parentObject = new JSONObject(a);
JSONArray results = parentObject.getJSONArray("results");
JSONObject resultsObject=results.getJSONObject(0);
JSONArray costsArray = resultsObject.getJSONArray("costs");
for (int i = 0; i < costsArray.length(); i++) {
Log.d("CostsJsonObject" , costsArray.getJSONObject(i).toString());
}
} catch (JSONException e) {
Log.d("CostsJsonObject Exception" , e.toString());
}
And result :
I think your problem is on this code :
JSONObject mJsonObjectrng = jsonObjsstorng.getJSONObject(k);
Simply change it to :
JSONObject mJsonObjectrng = jsonObjsstorng.getJSONObject(0);
Hope it'll help you ;)

How to Sort json Object key in sequence order?

Here is my json structure
{
"menus": [
{
"sequence":"1",
"Name":"Sector"
},
{
"sequence":"3",
"Name":"Segment"
},
{
"sequence":"2",
"Name":"Collection"
}
]
}
How to parse/storing data like 1,2,3 in sequence order?
Parse your array in a list
JSONArray sortedJsonArray = new JSONArray();
List<JSONObject> jsonList = new ArrayList<JSONObject>();
for (int i = 0; i < jsonArray.length(); i++) {
jsonList.add(jsonArray.getJSONObject(i));
}
then use collection.sort to sort the newly created list
Collections.sort( jsonList, new Comparator<JSONObject>() {
public int compare(JSONObject a, JSONObject b) {
String valA = new String();
String valB = new String();
try {
valA = (String) a.get("sequence");
valB = (String) b.get("sequence");
}
catch (JSONException e) {
//do something
}
return valA.compareTo(valB);
}
});
Insert the sorted values in your array
for (int i = 0; i < jsonArray.length(); i++) {
sortedJsonArray.put(jsonList.get(i));
}
Create a Object class & initiate variable's,like bellow & apply getter & setter like below.
class Menus
{
private String sequence;
private String Name;
public String getSequence()
{
return sequence;
}
public void setSequence(String sequence)
{
this.sequence= sequence;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.Name= name;
}
}
2.Then parse your Json Values like bellow
Intitiate the list as Menus list;
List menuslist = new ArrayList();
try{
JSONObject jObject = new JSONObject(result.toString);
JSONArray array =jObject.getJSONArray("menus");
for(int i=0; i
JSONObject Object = array.JSONObject(i);
Menus menus = new Menus();
menus.setSequence(Object.getString("sequence"));
menus.setName(Object.getString("name"));
menuslist.add(menus);
}
}
catch(JSONException Je)
{
je.printexception;
}
I did using TreeMap.
Map sequenceMenuOrder = new TreeMap<String, String>();
int position = 0;
for (int index = 0; index < menus.length(); index++) {
sequenceMenuOrder.put(menus.getJSONObject(index).getString("sequence"), menus.getJSONObject(index).getString("menuName"));
}
for (Object value : sequenceMenuOrder.keySet()) {
if (position != 0) {
menuString += ",";
}
menuString += sequenceMenuOrder.get(value);
position++;
}

Android : parse a JSONArray

I would need help to parse this JSONArray in my Android app. I'm a bit confused with JSONObjects and JSONArrays :
[
{
"nid": [
{
"value": "3"
}
],
"uid": [
{
"target_id": "1",
"url": "/user/1"
}
],
"field_image": [
{
"target_id": "2",
"alt": "alternate 1",
"title": "",
"width": "640",
"height": "640",
"url": "http://url"
},
{
"target_id": "3",
"alt": "alternate 2",
"title": "",
"width": "640",
"height": "640",
"url": "http://url"
}
]
}]
Here is what I've got to start the iteration :
public void onResponse(JSONArray response) {
try {
jsonResponse = "";
for (int i = 0; i < response.length(); i++) {
...
Here is your code to parse data,
private void parseData(){
try {
JSONArray jsonArray=new JSONArray(response);
JSONObject jsonObject=jsonArray.getJSONObject(0);
JSONArray jsonArrayNid=jsonObject.getJSONArray("nid");
JSONArray jsonArrayUid=jsonObject.getJSONArray("uid");
JSONArray jsonArrayField_image=jsonObject.getJSONArray("field_image");
for(int i=0;i<jsonArrayNid.length();i++){
JSONObject jsonObjectNid=jsonArrayNid.getJSONObject(i);
String value=jsonObjectNid.getString("value"); //here you get your nid value
}
for(int i=0;i<jsonArrayUid.length();i++){
JSONObject jsonObjectUid=jsonArrayUid.getJSONObject(i);
String target_id=jsonObjectUid.getString("target_id"); //here you get your uid target_id value
String url=jsonObjectUid.getString("url"); //here you get your uid url value
}
for(int i=0;i<jsonArrayField_image.length();i++){
JSONObject jsonObjectFieldImage=jsonArrayField_image.getJSONObject(i);
String target_id=jsonObjectFieldImage.getString("target_id");
String alt=jsonObjectFieldImage.getString("alt");
String title=jsonObjectFieldImage.getString("title");
String width=jsonObjectFieldImage.getString("width");
String height=jsonObjectFieldImage.getString("height");
String url=jsonObjectFieldImage.getString("url");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
for (int i = 0; i < response.length(); i++) {
JSONObject tobject = response.getJSONObject(i);
JSONArray nid = tobject.getJSONArray("nid");
JSONArray uid= tobject.getJSONArray("uid");
JSONArray field_image= tobject.getJSONArray("field_image");
//similarly you can loop inner jsonarrays
}
Use code according to you:
JSONArray array = null;
try {
array = new JSONArray(url); // your web url
JSONObject object = array.getJSONObject(0);
JSONArray array1 = object.getJSONArray("nid");
JSONObject object1 = array1.getJSONObject(0);
String value = object1.getString("value");
JSONArray array2 = object.getJSONArray("uid");
JSONObject object2 = array2.getJSONObject(0);
String target = object2.getString("target_id");
String url = object2.getString("url");
JSONArray array3 = object.getJSONArray("field_image");
JSONObject object3 = array3.getJSONObject(0);
String alt = object3.getString("alt");
Toast.makeText(Testing.this,value+"\n"+target+"\n"+url+"\n"+alt,Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
Try to parse like this.
In this code, jsonArray is the parent array which you have in your JSON.
for(int i=0;i<jsonArray.length();i++)
{
try {
JSONObject object=jsonArray.getJSONObject(i);
JSONArray imageArray=object.getJSONArray("field_image");
for(int j=0;j<imageArray.length();j++)
{
JSONObject imageObject=imageArray.getJSONObject(j);
String targetId=imageObject.getString("target_id");
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
Now :) if you have to parse something first look for some library:
http://www.java2s.com/Code/Jar/g/Downloadgson222jar.htm
Download gson.jar and then create java classes that mimic your desired json:
class C1{
private String value;
}
class C2{
private String target_id;
private String url;
}
class C3{
private String target_id;
private String alt;
private String title;
private String width;
private String height;
private String url;
}
class c4{
private List<C1> nid;
private List<C2> uid;
private List<C3> field_image;
}
Since you receive array from C4, you parse it like this:
public void onResponse(JSONArray response){
String value = response.toString();
GsonBuilder gb = new GsonBuilder();
Type arrayType = new TypeToken<List<C4>>() {}.getType();
List<C4> data = gb.create().fromJson(value, arrayType);
}
So in just 3 lines of code, you have your entire json serialized to java objects that you can use in your code.
Try
public void onResponse(JSONArray response) {
try {
if (response != null) {
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = resultsArray.getAsJsonObject(i);
//get nid array
JSONArray nidJSONArray = jsonObject.getJSONArray("nid");
//get uid array
JSONArray uidJSONArray = jsonObject.getJSONArray("uid");
//get field_image array
JSONArray fieldImageJSONArray = jsonObject.getJSONArray("field_image");
//parse nid array
if (nidJSONArray != null) {
for (int i = 0; i < nidJSONArray.length(); i++) {
JSONObject jsonObject = nidJSONArray.getAsJsonObject(i);
String value = jsonObject.getString("value");
}
}
//parse uid array
if (uidJSONArray != null) {
for (int i = 0; i < uidJSONArray.length(); i++) {
JSONObject jsonObject = uidJSONArray.getAsJsonObject(i);
String targetId = jsonObject.getString("target_id");
String url = jsonObject.getString("url");
}
}
//parse field_image array
if (fieldImageJSONArray != null) {
for (int i = 0; i < fieldImageJSONArray.length(); i++) {
JSONObject jsonObject = fieldImageJSONArray.getAsJsonObject(i);
String targetId = jsonObject.getString("target_id");
String alt = jsonObject.getString("alt");
String title = jsonObject.getString("title");
String width = jsonObject.getString("width");
String height = jsonObject.getString("height");
String url = jsonObject.getString("url");
}
}
}
}
} catch(Exception e) {
Log.e("Error", e.getMessage());
}
}

Parsing nested arrays in array

I've usually use Retrofit to do all parsing "dirty" work, but recently I've decided to parse json "by the hands". And I can't figure out how to parse nested arrays in array, there is my json:
[
{
"title":"Phone",
"subs":[
{
"id":157291,
"title":"Cell Phone Service"
},
{
"id":524624,
"title":"Landline Phone Service"
},
{
"id":157298,
"title":"Voice Over IP"
}
]
},
{
"title":"TV and Internet",
"subs":[
{
"id":157292,
"title":"Hardwire Internet"
},
{
"id":178472,
"title":"Television"
},
{
"id":524625,
"title":"Wireless Internet"
}
]
},
{
"title":"Entertainment",
"subs":[
{
"id":522695,
"title":"Music and Movies"
}
]
},
{
"title":"Bill Payment",
"subs":[
{
"id":179845,
"title":"Home Utilities"
}
]
},
{
"title":"Games and Social",
"subs":[
{
"id":157297,
"title":"Games",
"subs":[
{
"id":525000,
"title":"Category:Casual"
},
{
"id":525001,
"title":"Category:Online Games"
},
{
"id":525002,
"title":"Category:Action and Shooter Games"
},
{
"id":525003,
"title":"Category:RPG"
},
{
"id":525005,
"title":"Category:Strategy"
},
{
"id":525006,
"title":"Category:Adventure"
},
{
"id":525008,
"title":"Category:Simulators"
},
{
"id":525171,
"title":"Category:Portals and Services"
},
{
"id":525265,
"title":"Category:Game artefacts"
}
]
},
{
"id":524626,
"title":"Social Networks"
},
{
"id":522901,
"title":"Dating"
}
]
},
{
"title":"Finances",
"subs":[
{
"id":522747,
"title":"Loan Repayment"
}
]
},
{
"title":"Everyday Purchases",
"subs":[
{
"id":288993,
"title":"Beauty, Health, and Sports"
}
]
},
{
"title":"Travel",
"subs":[
{
"id":523297,
"title":"Travel Reservations"
},
{
"id":524634,
"title":"Travel Agencies"
}
]
},
{
"title":"Websites",
"subs":[
{
"id":160550,
"title":"Advertising"
},
{
"id":233554,
"title":"Domain Hosting"
}
]
},
{
"title":"And also:",
"subs":[
{
"id":179843,
"title":"Charity"
},
{
"id":524635,
"title":"Online auctions"
},
{
"id":522887,
"title":"Miscellaneous"
}
]
}
]
I've got the second-level nested array, using this piece of code, but how can I get the third-level array?
String response = RequestManager.makeRequest();
StringBuilder sbResponse = new StringBuilder();
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
JSONArray nestedArray = jsonObject.getJSONArray("subs");
for (int j = 0; j < nestedArray.length(); j++) {
}
}
Log.d(LOG_TAG, sbResponse.toString());
} catch (JSONException e) {
e.printStackTrace();
}
And, by the way, how should I store this data in the database - I'm using Realm and I've created Category and SubCategory models, do I need to create another subcategory model for saving data from the third-level array?
Categoty model:
public class Category extends RealmObject {
#PrimaryKey
private String title;
private SubCategory subCategory;
//Getters and setters
}
And SubCategory model:
public class SubCategory extends RealmObject {
#PrimaryKey
private int id;
private String title;
//Getters and setters
}
String response = RequestManager.makeRequest();
StringBuilder sbResponse = new StringBuilder();
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
Category c=new Category();
JSONObject jsonObject = jsonArray.getJSONObject(i);
c.setTitle(jsonObject.getString("title"));
JSONArray nestedArray = jsonObject.getJSONArray("subs");
for (int j = 0; j < nestedArray.length(); j++) {
SubCategory s=new SubCategory();
JSONObject nestedObject= nestedArray.getJSONObject(i);
s.setId(nestedObject.getString("id"));
s.setTitle(nestedObject.getString("title"));
}
c.setSubCategory(s);
}
Log.d(LOG_TAG, sbResponse.toString());
} catch (JSONException e) {
e.printStackTrace();
}
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
JSONArray nestedArray = jsonObject.getJSONArray("subs");
for (int j = 0; j < nestedArray.length(); j++) {
JSONObject nestObj = nestedArray.getJSONObject(j);
if(nestObj.has("subs"))
{
JSONArray insideArray = nestObj.getJSONArray("subs");
for (int k = 0; k < insideArray .length(); k++) {
}
}
}
}
Log.d(LOG_TAG, sbResponse.toString());
} catch (JSONException e) {
e.printStackTrace();
}

Categories

Resources