I'm building an Android app for displaying school timetable, with the JSON data coming from a URL. However the JSON is formatted in a way that the needed arrays are inside a named "lessons" object. How would it be possible to get access to the arrays I need?
This is how my JSON looks
{
"week": "2019-04-01",
"times": {
"1": "07:00-08:29",
"2": "08:30-10:00",
"3": "10:15-11:45",
"4": "11:55-14:00",
"5": "14:10-15:40",
"6": "15:45-17:15",
"7": "17:20-18:50",
"8": "18:55-20:25",
"9": "20:35-22:05",
"lunch": "12:40-13:15"
},
"lessons": {
"2019-04-01": [{
"lesson": "2",
"start": "08:30",
"end": "10:00",
"subject": "PHP",
"group": "IS117",
"teacher": "Jane Doe",
"room": "A-222"
}
]
},
"last update": "2019-03-28 17:02:02"
}
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:
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.
Try this below code if it may help you.This will return jsonObject inside 2019-04-01 array.
JSONObject obj = new JSONObject("StringFormat"); JSONArray jsonarray = obj.getJSONArray("2019-04-01");