Nab Ilovich Nab Ilovich - 7 months ago 35
Android Question

How can I parse json using Java (android)

I have a JSON string and I need to extract a string from it using Java (android)

The JSON string look like that :

"Header": {
"context": {
"change": {
"token": 3191
"_jsns": "urn:zimbra"
"Body": {
"AuthResponse": {
"authToken": [
"_content": "token"
"lifetime": 43199998,
"_jsns": "urn:zimbraAdmin"
"_jsns": "urn:zimbraSoap"

I want to get the value of
, which is "token" is this case.

What i tried:
contains the json string

//result contains the json string
JSONObject jObject = new JSONObject(result);
String aJsonString = jObject.getString("Body");
JSONObject jResult = new JSONObject(aJsonString);
String aaa = jResult.getString("authToken");

At this point I get the following error :

W/System.err: org.json.JSONException: No value for authToken

Any help will be appreciated

EDIT : Java code updated


You need to traverse the JSON tree step by step

JSONObject jObject = new JSONObject(result); 
JSONObject jBody = jObject.getJSONObject("Body");
JSONObject jAuthResponse = jBody.getJSONObject("AuthResponse");
JSONArray jauthToken = jAuthResponse.getJSONArray("authToken");
JSONObject jFirst = jauthToken.getJSONObject(0);
String aJsonString = jObject.getString("_content");