How to access JSON array inside named object?

2019-08-19 04:39发布

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"
}

3条回答
倾城 Initia
2楼-- · 2019-08-19 04:46

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.

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-08-19 05:02

Try this below code if it may help you.This will return jsonObject inside 2019-04-01 array.

new JSONObject("YOUR RESPONSE STRING HERE").getJSONObject("lessons").getJSONArray("2019-04-01").getJSONObject(0)
查看更多
趁早两清
4楼-- · 2019-08-19 05:09

JSONObject obj = new JSONObject("StringFormat"); JSONArray jsonarray = obj.getJSONArray("2019-04-01");

查看更多
登录 后发表回答