0

I m using Eclipse and Android project. I have parsed the JSON and have contents as String. I have a JSON like:

{        
"state":{
"updated":"2012-07-16T19:20:30",
"value":604,
"variables":{
    "var1":12,
    "var2":47,
    "var3":77,
    "var4":77
    }
} 
}

I want to add "var5":value to JSON in Android. The value could be String, decimal,array, integer etc. I want to have the updated JSON as String. Can anyone help me?

0

1 Answer 1

2

Create a new JSONObject from the String by:

String str="{        
"state":{
"updated":"2012-07-16T19:20:30",
"value":604,
"variables":{
    "var1":12,
    "var2":47,
    "var3":77,
    "var4":77
    }
} 
}";
JSONObject jsonObject=new JSONObject(str);

now get JSONObject with key "variables" from this object by:

JSONObject variables=jsonObject.getJSONObject("variables");

to add a new value to this JSONObject use:

variables.put("var5", newValue);

now put this json object variables to jsonObject.

jsonObject.put("variables", variables);

and get This jsonObject as a String:

String strResult=jsonObject.toString();
Sign up to request clarification or add additional context in comments.

3 Comments

Ya I have done that. I have the old JSON contents in a String. But, how will I get the updated JSON as String(as I have to put it on server)? I m new to Android, so pls help even if my question is simple @jeet
you did that? you could have said.
I have iterated and able to see the new value in LogCat. But just want to know how will get a String variable of my new JSON?

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.