How To Access Json Array Inside Named Object?
Solution 1:
Try this below code if it may help you.This will return jsonObject inside 2019-04-01 array.
newJSONObject("YOUR RESPONSE STRING HERE").getJSONObject("lessons").getJSONArray("2019-04-01").getJSONObject(0)
Solution 2:
JSONObject obj = new JSONObject("StringFormat"); JSONArray jsonarray = obj.getJSONArray("2019-04-01");
Solution 3:
I recommend you use the GSON library to make life easier for you in case the JSON responses get more complex in the future. It does all the parsing of the JSON to a normal Java object for you.
First add this dependency in your gradle: implementation 'com.google.code.gson:gson:2.8.5'
Then create a java class/es that would represent the expected JSON structure. You can use this website to auto generate the java classes for you. You just copy/pase the JSON and it generates the JAVA code to construct your classes with constructors and getters/setters.
Then, you can just auto convert your received JSON object into your Java class.
Example:
Gson gson = new Gson();
JavaClass object = gson.fromJson(jsonObject.toString(), JavaClass.class);
- Then just access anything you want from that java object easily, instead of manually parsing the JSON objects that you receive.
N.B: I would also recommend you to start learning Retrofit networking library after that. It is considered to be a standard nowadays when doing REST API calls.
Post a Comment for "How To Access Json Array Inside Named Object?"