How to parse a JSON array inside another JSON array in Android

Please help me .. I am working on a project and I am receiving data from web services in JSON format. I am trying to make it out, but I cannot do it. I have json-data data -

{ "response": { "status": { "code": "1", "message": "sucess", "user_id": "1" }, "foods": [ { "char": "A", "content": [ { "food_name": "add Malt" }, { "food_name": "a la mode" }, { "food_name": "Almonds" } ] }, { "char": "Z", "content": [ { "food_name": "Zebra Cakes" }, { "food_name": "Zucchini, Baby" }, { "food_name": "zxc" } ] } ] } } 

From here, I can successfully get the Array โ€œproductsโ€, but I get stuck when I try to get the โ€œcontentโ€ array and the food_name data.

I am using this code, but I have not received any solution, please check this snippet.

 protected String doInBackground(String... args) { // Building Parameters List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("method","eat_tracking_details")); nameValuePairs.add(new BasicNameValuePair("uid",userid)); // getting JSON string from URL JSONObject json = jsonParser.makeHttpRequest(JSONParser.urlname,"GET", nameValuePairs); //System.out.println("****json*"+json); if (json != null) { try { JSONObject response = json.getJSONObject("response"); JSONObject status = response.getJSONObject("status"); code = status.getString("code"); JSONArray FoodArray = response.getJSONArray("foods"); for (int i = 0; i < FoodArray.length(); i++) { String character = FoodArray.getJSONObject(i).getString("char"); System.out.println("*****character****************"+character); JSONArray FoodNameArray = new JSONArray(FoodArray.getJSONObject(i).getString("content")); System.out.println("====================///////////"+FoodNameArray); for (int j = 0; j <FoodNameArray.length(); j++) { String Foodname = FoodArray.getJSONObject(j).getString("food_name"); System.out.println("@@@@@@@@@@@@@"+Foodname); } } } catch (JSONException e) { // TODO: handle exception } } 

Check this web service response url , web service url

+6
source share
2 answers

You need to replace the corresponding part of the code with this code:

 for (int j = 0; j < FoodNameArray.length(); j++) { String Foodname = FoodNameArray.getJSONObject(j).getString("food_name"); System.out.println("@@@@@@@@@@@@@" + Foodname); } 
+3
source

I believe the best approach would be to use the GSON library ( http://code.google.com/p/google-gson/ ). In this case, you just need to make your model classes and not worry about the parsing logic.

+2
source

Source: https://habr.com/ru/post/955959/


All Articles