3

I am making an android app and have to use json. I am very new to JSON so I have a question. I have got the following json code from a HttpUrlConnection:

 [{"id":"12","name":"John","surname":"Doe","age":"23","username":"123"}]

How can I convert this string to a jsonArray and get the "23" out of this array using java? I already searched a lot on stackoverflow but didn't got the right answer. Hope somebody could help me.

I already tried to make it an jsonObject but it didn't work. Result is the string I've got from the HttpUrlConnection:

JSONObject jsonObject = new JSONObject(result);
String jsonname = jsonObject.getString("age");
4
  • Which JSON library are you using? Commented Apr 25, 2016 at 13:33
  • I am using android studio. I thought Json was already build in android studio Commented Apr 25, 2016 at 13:37
  • What's the fully qualified name of the JsonObject class, just to be sure which one you're using? Commented Apr 25, 2016 at 13:38
  • I suspect you'll need to instantiate a JsonArray, rather than a JsonObject. The string above is an array, which you should then be able to interrogate for its individual items. Commented Apr 25, 2016 at 13:40

1 Answer 1

7

The JSON string you've supplied is an array (containing a single element). Try using this instead:

JSONArray jsonArray = new JSONArray(result);

// This gets you the first (zero indexed) element of the above array.
JSONObject jsonObject = jsonArray.getJSONObject(0);
String age = jsonObject.getString("age");

Similar to this question, but you have the opposite problem.

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

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.