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();
}
Related
I am creating sectioned recyclerview list.using server response
one for header and second for child how to add it dynamically in my sectioned recyclerview but when i am getting output in recyclerview last record inserted two time with childlist.
there is two json arrays from server like this
"status": "1",
"msg": "Success",
"resident": {[
"wing_id": "4",
"resident_details": [
{
"first_name": "Suraj",
"last_name": "Jumbad",
"wing_id": "4",
},
{
"first_name": "Laxman ",
"last_name": "Kathar",
"wing_id": "4",
}
]
}
here is my code
try {
if (response.has("status") && response.getString("status").equals("1")) {
JSONArray residents = response.getJSONArray("resident");
for (int i = 0; i < residents.length(); i++) {
JSONObject jsonObject_residents_details = residents.getJSONObject(i);
String wing_name = jsonObject_residents_details.getString("wing_name");
String wing_id = jsonObject_residents_details.getString("wing_id");
sectionHeaderss.add(new SectionHeader(child, wing_name, i));
JSONArray resident_details = jsonObject_residents_details.getJSONArray("resident_details");
for (int j = 0; j < resident_details.length(); j++) {
JSONObject jsonObject = resident_details.getJSONObject(j);
String wing_ids = jsonObject.getString("wing_id");
String first_name = jsonObject.getString("first_name");
childList.add(new Child(first_name, wing_ids, wing_name));
//child add
//sectionHeaderss.add(new SectionHeader(childList, wing_name, i));
}
//main add
if (!childList.isEmpty()) {
for (int k = 0; k < childList.size(); k++) {
if (childList.get(k).getId().equals(wing_id)) {
sectionHeaderss.add(new SectionHeader(childList, wing_name, i));
}
}
} else {
sectionHeaderss.add(new SectionHeader(child, wing_name, i));
}
}
adapterRecycler = new AdapterSectionRecycler(GroupListActivity.this, sectionHeaderss);
rv_resident_list.setAdapter(adapterRecycler);
if (adapterRecycler != null) {
adapterRecycler.notifyDataSetChanged();
}
} else {
Toast.makeText(GroupListActivity.this, response.get("msg").toString(), Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
Toast.makeText(GroupListActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
Functions.pbVisiblity(true, pb_rv_resident_list);
}
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
Im getting problems with parsing Json.
my json response.
{
"Persons": [
{
"id": 0,
"name": "William",
"image": "http://www.images-image2312321356.jpg",
"colors": [
"White",
"Red",
"Green"
]
},
{...}
Im trying this. but it causes a compile error
public void onResponse(JSONObject responseObject) {
try {
JSONArray rs = responseObject.getJSONArray("Persons");
for (int i = 0; i < rs.length(); i++) {
try {
final JSONObject c = rs.getJSONObject(i);
String name = c.getString("name");
items.add(name);
));
}
} catch (JSONException e) {
e.printStackTrace();
}
Any idea? Im using volley
public void onResponse(JSONObject responseObject) {
JSONArray rs = responseObject.getJSONArray("Persons");
if (rs != null || rs.length() > 0) {
for (int i = 0; i < rs.length(); i++) {
JSONObject obj = rs.getJSONObject(i);
String id = obj.getString("id");
String name = obj.getString("name");
String img = obj.getString("image");
JSONArray colors = obj.getJSONArray("colors");
for (int ii = 0; ii < colors.length(); ii++) {
String color = colors.getString(ii);
colors.add(color);
}
}
}
}
I want to get only some selected values from the JSON response.For example if JSON contains 100 string values then i need to take the values which are starting with # symbol from that 100 values.
How can I do that ?
Following is my JSON,
[{"Obj" :
{ "ID":"11",
"NAME":"XYZ",
"GENDER":"M"
}
{ "ID":"11",
"NAME":"#XYZ",
"GENDER":"M"
}
{ "ID":"11",
"NAME":"#XYZ",
"GENDER":"M"
}
}]
Here I need to fetch Name which having # symbol
You can use below method to get the Name which start with # :
JSONObject jsonObject = new JSONObject(response);// u can change it as per your need
JSONArray jArray = jsonObject.getJSONArray("Obj");// if your `Obj` is an JsonArray
for (int i = 0; i < jArray.length(); i++) {
String json_name = jArray.getJSONObject(i).getString("NAME");
if(json_name.startsWith("#"))
{
Log.d(TAG,"It start with #");
}
}
Try out as below:
private void parseJSON(String json) {
try {
JSONArray items = new JSONArray(<your Json Response>);
for (int i = 0; i < items.length(); i++) {
JSONObject item = items.getJSONObject(i);
System.err.println("Object---" + item.getString("Obj"));
JSONObject obj=item.getJSONObject("Obj");
for (int j = 0; j < obj.length(); j++) {
String Name=obj.getString("NAME");
if(obj.getString("NAME").toString().contains("#"))
{
Log.d("Name starts with-->", Name);
}
else
{
Log.d("Name does not start with-->", Name);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
Try this.
first of all that's not a valid json may be below json is correct format
[
{
"Obj": [
{
"ID": "11",
"NAME": "XYZ",
"GENDER": "M"
},
{
"ID": "11",
"NAME": "#XYZ",
"GENDER": "M"
},
{
"ID": "11",
"NAME": "#XYZ",
"GENDER": "M"
}
]
}
]
if your response like above try below code this may help you.
try {
JSONArray jsoArray = new JSONArray(json);
JSONArray JobjArray = jsoArray.getJSONObject(0).getJSONArray("Obj");
for(int i=0; i < JobjArray.length(); i++)
{
JSONObject Jobj = JobjArray.getJSONObject(i);
Iterator<String> iter = Jobj.keys();
while (iter.hasNext()) {
String key = iter.next();
Log.v("key--", key);
try {
Object value = Jobj.get(key);
Log.v("value--", ""+value);
String str_value = value.toString().trim();
if(str_value.startsWith("#"))
{
Log.d(""+str_value,"value started with #");
}
} catch (JSONException e) {
// Something went wrong!
e.printStackTrace();
}
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
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! : )