0

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

2

3 Answers 3

1

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)
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.