0

I need to get the value of idinside studentarray. The response I get is,

{
  "response": {
      "student": [
        {
           "id": "125745",
           "module": 3,
           "status": 1
        }
      ]
   }
}

I tried using following code,

        String userId = null;
        try {
            JSONObject object = (JSONObject) new JSONTokener(response).nextValue();

            userId= object.getString("id");

        } catch (JSONException e) {
            e.printStackTrace();
        }

But it doesn't work. How do I retrieve id?

4 Answers 4

1

You are almost there, just you need to do this:

JSONArray students = object.getJSONArray("student");
JSONObject student = students.getJSONObject(0);
userId= student.getString("id");

Because the id value is placed in a JSONObject, then inside a JSONArray at index 0, then it is again placed inside a JSONObject.

Also don't forget to handle exceptions, the code above, is just for your understanding.

Hope that helps!!

Sign up to request clarification or add additional context in comments.

Comments

0

Your value is placed in json array. So, you need to retrieve response object using getJSONObject and then get student json array via getJSONArray. Then you will be able to iterate through student objects. There is no way to magically get id from json. Alternatively, you can map your json to Java objects using Gson, for example.

Comments

0

Try this :

Let all of the json is called

String serverResponse = "Response from the server";
try {
    JSONObject object = new JSONObject(serverResponse);
    String userId = object.getJSONObject("response").getJSONArray("student").getJSONObject(0).getString("id");
    }
catch (JSONException e) {
    e.printStackTrace();
}

Hope this helps.

Comments

0

Assuming jsonObject is a reference to your root json, you can get id of the first student:

JSONObject response = (JSONObject) jsonObject.get("response");
JSONArray students = (JSONArray) response.get("student");
int id = (int) ((JSONObject)students.get(0)).get("id");

Comments

Your Answer

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