Adding element to JSON in Android Eclipse - android

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?

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

Related

How parse json object and json array together

i have two situation of Json output .
one is data that found and i have a json array and a json object like this:
{"data":"yes"}[{"id":"10","number":"7","text":"text7","desc":"text7_again","user_code":"0"},{"id":"11","number":"8","text":"text8","desc":"text8_again","user_code":"1"}]
other situation is that data not found :
{"data":"no"}
just one json object.
how parse this data in android client for support two situtaion?
First, you should validate your json in http://jsonlint.com/ if you test it you will look that is a wrong json. So, for make it right, in your server your response should look something like this:
{"data":"yes","response":[{"id":"10","number":"7","text":"text7","desc":"text7_again","user_code":"0"},{"id":"11","number":"8","text":"text8","desc":"text8_again","user_code":"1"}]}
And in that case, in android
JSONObject jsonObj = new JSONObject(response);
if (jsonObj.getString("data").compareTo("yes") == 0) {
JSONArray jsonArray = jsonObj.getJSONArray("response");
//To-Do another code
}
and that's all
Here is a possible case: (you need to fix your json format)
Success -
string resultJSON =
{"success":true,
"data":[
{"id":"10","number":"7","text":"text7","desc":"text7_again","user_code":"0"},
{"id":"11","number":"8","text":"text8","desc":"text8_again","user_code":"1"}]}
Failed -
string resultJSON =
{"success":false}
Then
JSONObject jsonRoot = new JSONObject(resultJSON);
bool isSuccess = jsonRoot.getBoolean("success");
if (isSuccess) {
// do the array parser
for(int i=0; i<jsonData.lenght;i++) {
JSONObject jsonObj = jsonData.getJSONObject(i);
String id = jsonObj.getString("id"); // get the value of id
String desc = jsonObj.getString("desc"); // and so on...
}
}

How can convert String to Json Array

I'm getting error cannot convert String to json object ..
While I'm converting this String
{"user_id": "user_id: 140" };
Error getting due to the format problem?
Thanks in advance..
try this JsonObject object=new JsonObject(jsonString); your string will be converted to JsonObject.
{"user_id": "user_id: 140" };
Please make sure that your json string is true.
Example JSON String:
[{"property":"value"}, {"property":"value"}, ...]
OR
{"property":[{"property":"value"}]}
OR
...
So may be your JSON String is not correct.
You can try with (Without ";" at the end of line)
{"user_id":"140"}
If you assign user_id: 140 as value then:
{"user_id":"user_id:140"}
Please make sure that at the end of line have no ;
And, how to parse JSON String???
The first {} => Object, [] => Array
Object without name
JSONObject jObject = new JSONObject(jsonString);
Object without name but in JSONArray
JSONObject jObject = jsonArray.getJSONObject(index); // example: index = 0
Object with name and in JSONArray
JSONObject jObject = jsonArray.getJSONObject("name_of_object");
JSONArray is like JSONObject & jsonArray above is an instance of JSONArray

Simple Json parsing in android

I got the Json response. I am not able to get the values from the string.my string is
Json_response is
{"NameAllList":[{"Current":{"time":"2012-02-21T08:04:21","Name":"abcd"},
"Next":{"Name":"data1","StartTime":"2012-02-21T08:06:21"}},{"Current":{"time":"2012-02-21T08:14:21","Name":"defg"},
"Next":{"Name":"data2","StartTime":"2012-02-21T08:24:21"}},{"Current":{"time":"2012-02-21T08:28:21","Name":"ghij"},
"Next":{"Name":"data3","StartTime":"2012-02-21T08:34:21"}},{"Current":{"time":"2012-02-21T08:40:21","Name":"knmo"},
"Next":{"Name":"data4","StartTime":"2012-02-21T08:48:21"}}]}
and i tried this.
JSONObject jsonObj = new JSONObject(json_response);
JSONObject subObj = jsonObj.getJSONObject("Current");
String name_current =subObj.getString("Name");
but i am not able to get the value of "Name". what mistake i have done. provide the link to do the above parsing.
first of all, your JSON response is having NameAllList as a JSON Array of objects.
So you have to fetch JSON Array first, then you can fetch one-by-one object.
for example:
JSONObject jsonString = (new JSONObject(json_response_string));
JSONArray array = jsonString.getJSONArray("NameAllList");
for(int i=0; i<array.length(); i++)
{
// Retrieve Current object as such
JSONObject objCurrent = array.getJSONObject("Current");
// Retrieve Next object as such
JSONObject objNext = array.getJSONObject("Next");
}
You are not parsing json properly, so you are not able to fetch value of Name. Please note JSON Annotation [] represent JSONArray, and {} respresent JSONObject, so method to get current item's name is:
JSONObject jsonObj = new JSONObject(json_response_string);
JSONArray jsonArr=jsonObj.getJSONArray("NameAllList");
String Hora_name_current="";
for(int i=0;i<jsonArr.length();i++)
{
JSONObject obj=jsonArr.get(i);
try{
JSONObject subObj = obj.getJSONObject("Current");
Hora_name_current =subObj.getString("Name");
break;
}catch(JSONException ex)
{
}
}
looks like you're trying to use JSONObject when you should be using JSONArray for the second request. Try this:
JSONObject jsonString = (new JSONObject(json_response_string));
JSONArray array = jsonString.getJSONArray("NameAllList");
In your JSON return, "NameAllList is actually an array and needs to be handled as such. Once you set it to "array", you can then run a for loop and treat it like any other array in Java.
Let me know if that helps.
David
JSONObject jsonObj = new JSONObject(json_response_string);
JSONArray jsonArray = jsonObj.getJSONArrays("NameAllList");

Android JSON Object

I have a JSON format like this
{"response":{"status":true,"result":"user_exists"}}
Now i am trying to retrieve the Status value to do some logic
JSONObject jData = new JSONObject(data);
JSONArray response = jData.getJSONArray("response");
But i am getting the following error
org.json.JSONException: Value {"result":"user_exists","status":true}
at response of type org.json.JSONObject cannot be converted to
JSONArray
how to retrieve an Object from inside and Object ?
response is a JSONObject, not a JSONArray. Array objects are surrounded by these [] brackets, objects are with the normal ones {}. (See json.org for more format information)
Change
JSONArray response = jData.getJSONArray("response");
to
JSONObject response = jData.getJSONObject("response");
you are trying to retreive the status attribut from a JSONArray but , you don't have any JSONArray in your Code , ( JSONArray is surrounded by [] , and JSONObject is surrounded by {} ) ,
So to retreive the status value , try this :
JSONObject jData = new JSONObject(data);
JSONObject response = jData.getJSONObject("response");
boolean status = response.getBoolean("status");
response isn't an array but an object. Use getJSONObject and JSONObject instead of getJSONArray and JSONArray.
You have to first navigate to the response object by
JSONObject response = jData.getJSONObject("response") instead of JSONArray, as response is a object.

JSON Traversing to element using Json webservices in android

I am taking result of a json webservice in JSONObject. While printing this jsonObject it is printing exact result. I got problem at the time of fetching values in this result because i am reading a complex response that is in the form of
{"FoodMenuRS"
:{"Status":"Success",
"TotalResults":2,
"Results":{"Items":
{"Item":[
{"#Id":"6","#Name":"Tea"},
{"#Id":"4","#Name":"Coffee"}
]}}}}
Here i am reading through,
JSONArray jsonArray = json.getJSONArray("Item");
Here i am getting error "No Value for Item"
Where as i got fetched value while calling another service which is simple in format,
{"earthquakes":
[{"eqid":"c0001xgp","magnitude":8.8,"lng":142.369,"src":"us","datetime":"2011-03-11 04:46:23","depth":24.4,"lat":38.322},
{"eqid":"2010xkbv","magnitude":7.5,"lng":91.9379,"src":"us","datetime":"2010-06-12 17:26:50","depth":35,"lat":7.7477}]}
I called it using,
JSONArray earthquakes = json.getJSONArray("earthquakes");
Please help how to fetch this type of Json response. Thanks in advance.
ya it is very complex but i refer you to use Gson library to parse Json as it is parse in structural manner example
check this:
http://www.androidcompetencycenter.com/2009/10/json-parsing-in-android/
Done with
JSONObject menuObject = jObject.getJSONObject("menu");
String attributeValue = menuObject.getString("value");
private String jString = "{\"menu\": {\"id\": \"file\", \"value\": \"File\", \"popup\": { \"menuitem\": [ {\"value\": \"New\", \"onclick\": \"CreateNewDoc()\"}, {\"value\": \"Open\", \"onclick\": \"OpenDoc()\"}, {\"value\": \"Close\", \"onclick\": \"CloseDoc()\"}]}}}";
JSONObject menuObject = jObject.getJSONObject("menu");
String attributeId = menuObject.getString("id");
String attributeValue = menuObject.getString("value");
JSONObject popupObject = menuObject.getJSONObject("popup");
JSONArray menuitemArray = popupObject.getJSONArray("menuitem");
With every new curley braces call getJSONObjectand for child call getString.
Or you can follow Gson concept to fetch response.

Categories

Resources