Issue initializing a JSONObject - android

I'm trying to initialize a JSONObject with the following string, received from a web service:
"{
"campaignid": "8",
"campaignname": "Pilotarienak 2011",
"campaignlink": "http:\\/\\/www.xxx.com\\/fr\\/cote-basque\\/agenda\\/2011-05-20\\/FMAAQU064FS016DV-pilotarienak-d-anglet?fromapp",
"splash": "http:\\/\\/www.xxx.com\\/ads\\/customers\\/pilotarienak\\/320x480.jpg",
"banner": "http:\\/\\/www.xxx.com\\/ads\\/customers\\/pilotarienak\\/320x160.jpg"
}"
It seems to be valid json (it validates in jsonlint.com), but when initializing a JSONObject with that I get:
org.json.JSONException: Value of type java.lang.String cannot be converted to JSONObject
Anybody can help?
Thanks

Seems like you are trying to instantiate it from a String with extra quotes. You need to remove the wrapping quotes(I'm not using your string, but giving an example to make it clearer):
This is OK:
String jStr= "{\"param1\":\"hello\"}";
JSONObject jObj = new JSONObject(jStr);
This is not:
String jStr= "\"{\"param1\":\"hello\"}\"";
// note this ^^ and this ^^
JSONObject jObj = new JSONObject(jStr);

Try to rewrite all, in a simplified mode (just for test). I think that you put some invalid character.

Try to remove All the "\" caracters

Related

at user of type java.lang.String cannot be converted to JSONObject json response android

the Response From Server is:
{"message":"Login successfull","error":false,"user":"{\"DISTRICT\":[{\"Id\":1,\"Name\":\"Abbottabad\"},{\"Id\":3,\"Name\":\"Bannu\"},{\"Id\":4,\"Name\":\"DI Khan\"},{\"Id\":5,\"Name\":\"Kohat\"},{\"Id\":6,\"Name\":\"Mardan\"},{\"Id\":7,\"Name\":\"Peshawar\"},{\"Id\":8,\"Name\":\"Swat\"},{\"Id\":9,\"Name\":\"Battagram\"},{\"Id\":10,\"Name\":\"Buner\"},{\"Id\":11,\"Name\":\"Chitral\"},{\"Id\":12,\"Name\":\"Charsadda\"},{\"Id\":13,\"Name\":\"Dera Ismail Khan\"},{\"Id\":14,\"Name\":\"Hangu\"},{\"Id\":15,\"Name\":\"Haripur\"},{\"Id\":16,\"Name\":\"Karak\"},{\"Id\":17,\"Name\":\"Kolai Pallas Kohistan\"},{\"Id\":18,\"Name\":\"Upper Kohistan\"},{\"Id\":19,\"Name\":\"Lower Kohistan\"},{\"Id\":20,\"Name\":\"Lakki Marwat\"},{\"Id\":21,\"Name\":\"Lower Dir\"},{\"Id\":22,\"Name\":\"Malakand\"},{\"Id\":23,\"Name\":\"Mansehra\"},{\"Id\":24,\"Name\":\"Nowshera\"},{\"Id\":25,\"Name\":\"Shangla\"},{\"Id\":26,\"Name\":\"Swabi\"},{\"Id\":27,\"Name\":\"Tank\"},{\"Id\":28,\"Name\":\"Upper Dir\"},{\"Id\":29,\"Name\":\"Torghar\"}],\"BUSINESS_TYPE\":[{\"Id\":1,\"Name\":\"Hotels\"},{\"Id\":2,\"Name\":\"Restaurants\"},{\"Id\":3,\"Name\":\"Schools\\\/Colleges\"},{\"Id\":4,\"Name\":\"Dhaba\\\/Tea Stall\\\/Shwarma\\\/Dahi Bhalay\"},{\"Id\":5,\"Name\":\"Tandoor\"},{\"Id\":6,\"Name\":\"Juice Shop\"},{\"Id\":7,\"Name\":\"Kabab Shop\"},{\"Id\":8,\"Name\":\"Mega Marts\\\/Super Store\"},{\"Id\":9,\"Name\":\"Stores\"},{\"Id\":10,\"Name\":\"Karyana Store\"},{\"Id\":11,\"Name\":\"Fruits\\\/Dry Fruits\\\/Vegetables\"},{\"Id\":12,\"Name\":\"Meat Shop\"},{\"Id\":13,\"Name\":\"Poultry\\\/Fish Shop\"},{\"Id\":14,\"Name\":\"Whole Sale Dealer\"},{\"Id\":15,\"Name\":\"Distribution Point\"},{\"Id\":16,\"Name\":\"Wharehouse\"},{\"Id\":17,\"Name\":\"Bakers and Confectioners\"},{\"Id\":18,\"Name\":\"Small Industry\"},{\"Id\":19,\"Name\":\"Medium Industry\"},{\"Id\":20,\"Name\":\"Large Industry\"},{\"Id\":21,\"Name\":\"Cottage Industry\"},{\"Id\":22,\"Name\":\"Cart\"},{\"Id\":23,\"Name\":\"Cold Storage\"},{\"Id\":24,\"Name\":\"Slaughter House\"},{\"Id\":25,\"Name\":\"Dairy Shop and Form\"},{\"Id\":26,\"Name\":\"Canteen\"},{\"Id\":27,\"Name\":\"Others\"},{\"Id\":28,\"Name\":\"Oil\\\/Ghee Industry\"},{\"Id\":29,\"Name\":\"Ice Factory\"},{\"Id\":30,\"Name\":\"Salt and Minerals\"},{\"Id\":31,\"Name\":\"Ice Cream Factory\"},{\"Id\":32,\"Name\":\"Water Purification Plant\"},{\"Id\":33,\"Name\":\"Masala\"},{\"Id\":34,\"Name\":\"Papar Factory\"},{\"Id\":35,\"Name\":\"Papar\\\/Chips\\\/Pops Factory\"}],\"ASSISTANT_DIRECTOR\":[{\"staff_id\":1,\"staff_name\":\"Sajjad Ahmad\"},{\"staff_id\":2,\"staff_name\":\"Murad Ali\"}],\"FSO\":[{\"staff_id\":35,\"staff_name\":\"Shahab\"},{\"staff_id\":36,\"staff_name\":\"Shakeel Ahmad Khan\"},{\"staff_id\":37,\"staff_name\":\"Nawab Ali\"},{\"staff_id\":38,\"staff_name\":\"Shakeel Ahmed\"}],\"OFFENCE\":[{\"Id\":1,\"Name\":\"Adultration\"},{\"Id\":2,\"Name\":\"Mislabeling\\\/Misbranding\"},{\"Id\":4,\"Name\":\"Unhygienic Condition\"},{\"Id\":5,\"Name\":\"Banned Items\"},{\"Id\":6,\"Name\":\"Expired Items\"}],\"SAMPLE_DISCARDED\":[{\"Id\":1,\"Name\":\"Milk\"},{\"Id\":2,\"Name\":\"Meat\"},{\"Id\":3,\"Name\":\"Water\"},{\"Id\":4,\"Name\":\"Beverages\"},{\"Id\":5,\"Name\":\"Diary Products\"},{\"Id\":6,\"Name\":\"Poultry\"},{\"Id\":7,\"Name\":\"Salt\"},{\"Id\":8,\"Name\":\"Spices\\\/Masala\"},{\"Id\":9,\"Name\":\"Bakary\"},{\"Id\":11,\"Name\":\"Chips\\\/Pops\"},{\"Id\":12,\"Name\":\"Oil\\\/Ghee\"},{\"Id\":13,\"Name\":\"Ice\"},{\"Id\":14,\"Name\":\"Non-Food Colors\\\/Flavours\"},{\"Id\":15,\"Name\":\"Fruit Pulp\\\/Squash\\\/Jams\\\/Pickles\"}]}"}
What I am trying to do is:
JSONObject obj = new JSONObject(s);
JSONObject userJson = obj.getJSONObject("user");
which Give the Correct Result with Exception which is:
W/System.err: org.json.JSONException: Value {"DISTRICT":[{"Id":1,"Name":"Abbottabad"},{"Id":3,"Name":"Bannu"},{"Id":4,"Name":"DI Khan"},{"Id":5,"Name":"Kohat"},{"Id":6,"Name":"Mardan"},{"Id":7,"Name":"Peshawar"},{"Id":8,"Name":"Swat"},{"Id":9,"Name":"Battagram"},{"Id":10,"Name":"Buner"},{"Id":11,"Name":"Chitral"},{"Id":12,"Name":"Charsadda"},{"Id":13,"Name":"Dera Ismail Khan"},{"Id":14,"Name":"Hangu"},{"Id":15,"Name":"Haripur"},{"Id":16,"Name":"Karak"},{"Id":17,"Name":"Kolai Pallas Kohistan"},{"Id":18,"Name":"Upper Kohistan"},{"Id":19,"Name":"Lower Kohistan"},{"Id":20,"Name":"Lakki Marwat"},{"Id":21,"Name":"Lower Dir"},{"Id":22,"Name":"Malakand"},{"Id":23,"Name":"Mansehra"},{"Id":24,"Name":"Nowshera"},{"Id":25,"Name":"Shangla"},{"Id":26,"Name":"Swabi"},{"Id":27,"Name":"Tank"},{"Id":28,"Name":"Upper Dir"},{"Id":29,"Name":"Torghar"}],"BUSINESS_TYPE":[{"Id":1,"Name":"Hotels"},{"Id":2,"Name":"Restaurants"},{"Id":3,"Name":"Schools\/Colleges"},{"Id":4,"Name":"Dhaba\/Tea Stall\/Shwarma\/Dahi Bhalay"},{"Id":5,"Name":"Tandoor"},{"Id":6,"Name":"Juice Shop"},{"Id":7,"Name":"Kabab Shop"},{"Id":8,"Name":"Mega Marts\/Super Store"},{"Id":9,"Name":"Stores"},{"Id":10,"Name":"Karyana Store"},{"Id":11,"Name":"Fruits\/Dry Fruits\/Vegetables"},{"Id":12,"Name":"Meat Shop"},{"Id":13,"Name":"Poultry\/Fish Shop"},{"Id":14,"Name":"Whole Sale Dealer"},{"Id":15,"Name":"Distribution Point"},{"Id":16,"Name":"Wharehouse"},{"Id":17,"Name":"Bakers and Confectioners"},{"Id":18,"Name":"Small Industry"},{"Id":19,"Name":"Medium Industry"},{"Id":20,"Name":"Large Industry"},{"Id":21,"Name":"Cottage Industry"},{"Id":22,"Name":"Cart"},{"Id":23,"Name":"Cold Storage"},{"Id":24,"Name":"Slaughter House"},{"Id":25,"Name":"Dairy Shop and Form"},{"Id":26,"Name":"Canteen"},{"Id":27,"Name":"Others"},{"Id":28,"Name":"Oil\/Ghee Industry"},{"Id":29,"Name":"Ice Factory"},{"Id":30,"Name":"Salt and Minerals"},{"Id":31,"Name":"Ice Cream Factory"},{"Id":32,"Name":"Water Purification Plant"},{"Id":33,"Name":"Masala"},{"Id":34,"Name":"Papar Factory"},{"Id":35,"Name":"Papar\/Chips\/Pops Factory"}],"ASSISTANT_DIRECTOR":[{"staff_id":1,"staff_name":"Sajjad Ahmad"},{"staff_id":2,"staff_name":"Murad Ali"}],"FSO":[{"staff_id":35,"staff_name":"Shahab"},{"staff_id":36,"staff_name":"Shakeel Ahmad Khan"},{"staff_id":37,"staff_name":"Nawab Ali"},{"staff_id":38,"staff_name":"Shakeel Ahmed"}],"OFFENCE":[{"Id":1,"Name":"Adultration"},{"Id":2,"Name":"Mislabeling\/Misbranding"},{"Id":4,"Name":"Unhygienic Condition"},{"Id":5,"Name":"Banned Items"},{"Id":6,"Name":"Expired Items"}],"SAMPLE_DISCARDED":[{"Id":1,"Name":"Milk"},{"Id":2,"Name":"Meat"},{"Id":3,"Name":"Water"},{"Id":4,"Name":"Beverages"},{"Id":5,"Name":"Diary Products"},{"Id":6,"Name":"Poultry"},{"Id":7,"Name":"Salt"},{"Id":8,"Name":"Spices\/Masala"},{"Id":9,"Name":"Bakary"},{"Id":11,"Name":"Chips\/Pops"},{"Id":12,"Name":"Oil\/Ghee"},{"Id":13,"Name":"Ice"},{"Id":14,"Name":"Non-Food Colors\/Flavours"},{"Id":15,"Name":"Fruit Pulp\/Squash\/Jams\/Pickles"}]} at user of type java.lang.String cannot be converted to JSONObject
at org.json.JSON.typeMismatch(JSON.java:100)
I Tried a lot but can not find the solution.
The problem is that the value for the key "user" is not actually a json object, it is a String that looks like a json object. This is what you have, formatted and trimmed a little bit:
"user":"{\"DISTRICT\":[...]}"
If this were a json object, it would look like this instead:
"user":{"DISTRICT":[...]}
The double-quotes surrounding the curly braces, as well as the backslashes escaping the double-quotes inside the curly braces, are clues that you're actually working with a String here.
What you could do is retrieve the value of "user" as a String, but then convert it to a json object:
JSONObject obj = new JSONObject(s);
String userString = obj.getString("user");
JSONObject userObject = new JSONObject(userString);

how to get data from serialize json array

{
"id": "1",
"name": "test1",
"data_city": "a:35: {i:22;s:6:\"61,800\";i:23;s:6:\"61,800\";i:24;s:6:\"61,800\";i:25;s:6:\"61,800\" ;i:26;s:6:\"61,800\";i:27;s:6:\"61,800\";i:28;s:6:\"61,800\";i:29;s:6:\"61,800\";i:30;s:6:\"61,800\";i:31;s:6:\"61,800\";i:54;s:6:\"61,800\";i:16;s:6:\"61,800\";i:32;s:6:\"61,800\";i:52;s:6:\"61,800\";i:21;s:6:\"61,800\";i:33;s:6:\"61,800\";i:37;s:6:\"61,800\";i:34;s:6:\"61,800\";i:36;s:6:\"61,800\";i:38;s:6:\"61,800\";i:41;s:6:\"61,800\";i:35;s:6:\"61,800\";i:39;s:6:\"61,800\";i:40;s:6:\"61,800\";i:42;s:6:\"61,800\";i:44;s:6:\"61,800\";i:43;s:6:\"61,800\";i:46;s:6:\"61,800\";i:45;s:6:\"61,800\";i:47;s:6:\"61,800\";i:49;s:6:\"61,800\";i:53;s:6:\"61,800\";i:50;s:6:\"61,800\";i:48;s:6:\"61,800\";i:51;s:6:\"61,800\";}"
}
This is my json response
i need to get data from string data_city
First of all, your JSON is not valid - probably a copy paste error.
Anyway, there are several ways to do this. One option is to use the built in JSONObject type:
String jsonString = "YOUR_JSON_STRING";
JSONObject objJSON = new JSONObject(jsonString);
String dataCity = objJSON.getString("data_city");
Hope this helps. Be sure to run your JSON String through a validation tool first. This one works nicely: https://jsonformatter.curiousconcept.com/

Android Not Sure How To Refer To Value In JSON File (JSON Parsing)

Example JSON Page
http://maps.googleapis.com/maps/api/geocode/json?latlng=51.155455,-0.165058&sensor=true
#SuppressLint("NewApi")
public void readAndParseJSON(String in) {
try {
JSONObject reader = new JSONObject(in);
// This works and returns address
JSONArray resultArry = reader.getJSONArray("results");
String Address = resultArry.getJSONObject(1).getString("formatted_address").toString();
Log.e("Address", Address);
// Trying to get PostCode on code below - this is not working (log says no value at address components)
JSONArray postCodeArray = reader.getJSONArray("address_components");
String postCode = postCodeArray.getJSONObject(1).getString("long_name").toString();
Log.e("PostCode", postCode );
This code returns the address correctly. How can I get the post code long_name which is inside address_components?
Solution
I had to get each array, and then get the post code value.
I am using the value 7, as that is the JSONObject that has the postcode stored in the "long_name" field.
JSONObject readerJsonObject = new JSONObject(in);
readerJsonObject.getJSONArray("results");
JSONArray resultsJsonArray = readerJsonObject.getJSONArray("results");
JSONArray postCodeJsonArray = resultsJsonArray.getJSONObject(0).getJSONArray("address_components");
String postCodeString = postCodeJsonArray.getJSONObject(7).getString("long_name").toString();
Log.e("TAG", postCodeString);
Hope that helps.
reader.getJSONObject(1).getJSONArray("address_components");
Your problem is that results is a JSONArray that contains a child JSONObject composed of several children: "address_components", "formatted_address", "geometry", and "types". The result array actually contains many of these such objects, but let's focus on just the first child for now.
Look carefully at your code. With this line:
JSONArray resultArry = reader.getJSONArray("results");
You are getting the entire results. Later on, you then call the same method again:
JSONArray postCodeArray = reader.getJSONArray("address_components");
But you're asking for an "address_components" from the reader, where I do not expect you'll find anything (having already read the entire result before.) You should instead be working with the JSONArray you already got before, since it already contains the entire result.
Try something like:
JSONObject addressComponents = resultArry.getJSONObject(1).getJSONObject("address_components");
String postCode = addressComponents.getString("long_name");
Note: I don't know why you're singling out JSONObject #1 (as opposed to 0, which is the first, or any other one of them) and I also am not sure why you named the String postCode. So if I've misunderstood your intention, I apologize.
Is difficult to find the error... because all looks well. The problem maybe can exist when you make the json.put("address_components", something);
So my advice is put a breakpoint at this line
JSONArray postCodeArray = reader.getJSONArray("address_components");
o display the json in logcat
Log.d("Simple", reader.toString());
Then Paste your json in this web page to view more pretty
http://jsonviewer.stack.hu/
and check if all keys are stored well.
Solution
Need to get each array, and then get the post code value. The value 7 is used, as that is the JSONObject that has the postcode stored in the "long_name" field.
JSONObject readerJsonObject = new JSONObject(in);
readerJsonObject.getJSONArray("results");
JSONArray resultsJsonArray = readerJsonObject.getJSONArray("results");
JSONArray postCodeJsonArray = resultsJsonArray.getJSONObject(0).getJSONArray("address_components");
String postCodeString = postCodeJsonArray.getJSONObject(7).getString("long_name").toString();
Log.e("TAG", postCodeString);
Hope that helps.

How to Get JSONObject Only Android

{"StatusID":"1","Error":"Register Successfull."}
This my JSONObject I don't know how to convert it to string in android
Advice me Please
Thank.
Get the JSON object and get values like this.
JSONObject jsonObject = new JSONObject(res);
String statusId = jsonObject.getString("StatusID");
String error = jsonObject.getString("Error");
If you want just convert this json:
{"StatusID":"1","Error":"Register Successfull."}
you must use toString() method.
If you want get "status id" or "error" you should use getString() method
See THIS.

Trouble with Android JSONObject from Grails webservice

Okay I am quering data from a Grails webservice that returns JSON. The JSON when viewed with the JSONViewer app parses fine. When I take that same string and use JSONObject(string) in my Android app I get "value of String cannot be converted to JSONObject."
Here's my JSON string
[[{"class":"mygrails.TopTen","id":491,"ttAmount":14200000,"ttMlId":402,"ttRank":1,"ttWeekId":1108},{"class":"mygrails.MovieList","id":402,"mlApproved":1,"mlApprovedId":5,"mlMovieId":"GNOMEOAN","mlReleaseDate":"2011-03-08T07:41:45Z","mlTitle":"Gnomeo and Juliet","mlWeekId":1106}]]
Now the JSON is comes from the standard JSON conversion of a SQL data using render from the groovy file through the import grails.converters.JSON.
... //(call to render JSON in the groovy file)
def a
a = Table.findAll("from someTable as st where st.id=" params.id)
render a as JSON
...
So I am not sure what I doing wrong and why the JSON looks a little off to me. (still new to JSON)
In json if you see "[]" means its a json array and if you see "{}" it is an json object. Both of then can have the other nested inside then.
In your case the string the starts with json array.
So try something like the following
String str = "[[{"class":"mygrails.TopTen","id":491,"ttAmount":14200000,"ttMlId":402,"ttRank":1,"ttWeekId":1108},{"class":"mygrails.MovieList","id":402,"mlApproved":1,"mlApprovedId":5,"mlMovieId":"GNOMEOAN","mlReleaseDate":"2011-03-08T07:41:45Z","mlTitle":"Gnomeo and Juliet","mlWeekId":1106}]]";
JSONArray jsonArray = new JSONArray(str);
jsonArray = jsonArray.getJSONArray(0);
JSONObject jsonObject = jsonArray.getJSONObject(0);
String class = jsonObject.getString("class"); // class will value "mygrails.TopTen"
Try to create an JSONArray from the String instead of JSONObject. I didn't test this but that should do the trick: you have two nested arrays that contain then actual data.
Check out your JSON online with http://jsonformat.com/
http://www.freeformatter.com/json-formatter.html
JSON Viewer
http://jsonviewer.stack.hu/
Paste your text in there and you can see what you should parse:

Categories

Resources