L.B
L.B

Reputation: 51

Get string from jsonArray java android

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");

Upvotes: 3

Views: 15045

Answers (1)

ManoDestra
ManoDestra

Reputation: 6503

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.

Upvotes: 7

Related Questions