Get String from json with nested json object and nested json arrays with multiple json objects, in Android

I need to get as String all the single parameters contained in complex Json.

e.g. String people=...; String idPeople=...; String people=...; String idPeople=...; etc.

I tried to use JSONTokeners, as I tried to find a similar question, and for plain json I have no problems, but I don't know how to get the parameters from this correctly:

 {"id":1,"error":null,"result": {"nPeople":2, "people":[ {"namePeople":"Inca", "power":"1235", "location":"asdfghjja", "idPeople":189, "mainItems":"brownGem", "verified":false, "description":"Lorem impsum bla bla", "linkAvatar":"avatar_12.jpg", "longitude":16.2434263, "latitude":89.355118}, {"namePeople":"Maya", "power":"1235", "location":"hcjkjhljhl", "idPeople":119, "mainItems":"greenstone", "verified":false, "description":"Lorem impsum bla bla", "linkAvatar":"avatar_6.jpg", "longitude":16.2434263, "latitude":89.3551185}] } } 

NB the number of objects in an array of people is not always equal to 2 ... and can contain 4 or more people an object

+6
source share
2 answers

I have not tried. But I think it might work.

  JSONObject obj = new JSONObject(jsonString); String id = obj.getString("id"); String error = obj.getString("error"); JSONObject result = obj.getJSONObject("result"); int nPeople = result.getInt("nPeople"); JSONArray people = result.getJSONArray("people"); for(int i = 0 ; i < people.length() ; i++){ JSONObject p = (JSONObject)people.get(i); String namePeople = p.getString("namePeople"); ... } 
+20
source

if we call json, you publish myJsonString,

 JSonObject obj = new JSonObject(myJsonString); JSonObject result = obj.getJSONObject("result"); JSonArray people = result.getJSONArray("people"); int numOfPeople = result.getInt("nPeople"); 
+2
source

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


All Articles