JSONException: java.lang.String cannot be converted to JSONObject - android

I know this question has been asked a number of times but I didn't find any relative answer of my question.
I am trying to read json data from asset folder, but I'm getting following exception while getting
I searched number of stuffs but didn't help. Please give me any reference or hint.
Thanks in Advance.

Use
String searchedTerm = jsonObject.getString(TAG_SEARCHEDTERM);
JSONArray results = jsonObject.getJSONArray(TAG_RESULTS);
instead of
JSONObject searchedTerm = jsonObject.getJSONObject(TAG_SEARCHEDTERM);
JSONArray results = searchedTerm.getJSONArray(TAG_RESULTS);
because TAG_SEARCHEDTERM is key-value pair instead of JSONObject and you are trying to cast a String value to JsonObject.

I guess you need to get the Dish Name where you are getting exception.
You can get the dish name shown below...
String searchedTerm = jsonObject.getString(TAG_SEARCHEDTERM);
Using this
JSONArray results = jsonObject.getJSONArray(TAG_RESULTS);
you will get the "results" JSONArray as shown in your json file.
and you can iterate through it using for loop.

Related

JSONArray to JSONObject error from string using Gson

Many similar questions/answers out in SO but unfortunately I was unable to find an QA like mine that I could solve the problem with.
I have a function which accepts an array of objects. This array is changed to a string and then is supposed to return an JSONObject. The exact function is:
fun schoolsIdsToJson(schoolIds: ArrayList<Schools.schoolIds>): JSONObject {
val baseType: Type = object : TypeToken<ArrayList<Schools.schoolIds>>(){}.type
val gson = GsonBuilder().disableHtmlEscaping().create()
val json = gson.toJson(schoolIds, baseType) //, baseType
var jsonResp: String = json.toString()
jsonResp = jsonResp.replace("\"[{]", "{")
jsonResp = jsonResp.replace("[}]\"", "}")
Log.e("schoolsIdsToJson", jsonResp)
return JSONObject(jsonResp)
}
When I log jsonResp the string is [{"_id":626}] which is correct. But when I put the string into the JSONObject, it throws the error:
org.json.JSONException: Value [{"_id":626}] of type org.json.JSONArray cannot be converted to JSONObject
Now, I would expect this if I didn't change it to a string but when it's a string I'm confused as to why the error happens.
Any pointers of what I'm doing incorrectly?
Thanks,
^.^
UPDATE
Thx for everyone's help. The cause is that I was mixing things up. Took awhile for me to understand that. Here is the comment that sorted things out for me. Maybe it'll help someone else.
Again, you're mixing the things up: the variable is a Java string, but the data it holds is a JSON array that cannot be converted to a JSON object like that -- it is just illegal. Either make that method return JSONArray (or whatever appropriate from the org.json package; I haven't worked with it), or extract the first value from the result array (that does not make much sense in that code either)

Android JSONArray inside a JSONObject - type org.json.JSONObject cannot be converted to JSONArray

Im trying to get Data from a JSONObject that contains an array of user details
Im trying to get the username from this json
JSON Data
I can get the top level data easily with
JSONObject obj = response.getJSONObject(i);
Comment saving = new Comment();
saving.set_id(obj.getString("_id"));
saving.setDetail(obj.getString("details"));
saving.setVotes(obj.getInt("votes"));
How do i get the username value?
Thanks
The username key is again nested inside the JSON object you have in obj.
What you can do is
String username = obj.getJSONObject("user").getString("username");
Try this :
obj.getJSONObject("user").getString("username");
In yours IDE if you will press ctrl+space after obj with a dot (.) operator , you should get auto fill with various option to select .
the basic difference between JSONObject and JSONArray is following :
JSONArray starts with []
JSONObject starts with {}
As you can see the user is a JSONObject , hence obj.getJSONObject("user").getString("username");
I prefer decoding JSON like this instead of using third party library

Iterating through JsonObject in Java/Android. NOT JsonArray

Here's my JSON data sample:
{
"node_1.1":{
"someCrap":{
"someCrap":"SomeValue"
}
},
"node_1.2":{
"Node_1.2.1":{
"Node_1.2.1.1":{
"param1":value,
"param2":value,
"param3":"value",
"paramThatIneed":{
"ThisIsWhatIActuallyNeed":"url",
"width":96,
"height":72
}
},
"Node_1.2.1.2":{
Same as above, just that paramThatINeed might be missing, gotta place imagePlaceHolder Here
},
//and so on... there are a total of 50 of these..
}
}
}
Now I could get the node_1.1 and Node 1.2 and the sub-node of it node_1.2.1
However, there are 50 sub-nodes inside of node_1.2.1, and they will have random names returned from the server. Its in string format but they're actually ints. Its a page ID.
Now I wanna iterate through the node_1.2.1 and get those sub-nodes and access their sub-nodes and take in the URL of the paramThatINeed. If the paramThatINeed is not present, I need to put some null/dummy value.
This is the code that I tried to work it as far as I've reached:
JSONObject jsonObj = new JSONObject(jsonStr); //jsonStr is the entire JSON string
JsonObject node_1.2= jsonObj.getJsonObject("node_1.1");
JsonObject node_1.2.1 = node_1.2.getJsonObject("node_1.2.1");
What do I do after this? Because I can only getJsonObject by passing a string param to it, I tried using the for loop but it doesn't take any int param.
Also, as I said before, the nodes after that have random names and not fixed. So I'm totally confused.
Please help me out if you know how to solve this problem. Please remember there's no JsonArray in this. I'm probably thinking of editing the JSON string itself and replacing some parts of the '{' with '[' and converting it to an array :( ... I think that's a sad approach.
Use this to iterate over an object.
Android (JSONObject) How can I loop through a flat JSON object to get each key and each value
but be careful, from json object you won't get the result in original order, like in json array. The result will be in alphabetical order (I hope I was clear). And you can use optJsonobject(), instead of getJsonObject(). It will returns null, instead of throw exception. You can use opt every where instead of get.

JSON Array or Object Error in Android

I have a string being returned from a HttpClient called data.
Data = {"result":[{"id":"2","contextID":"1","name":"Kitchen","image":"81"},
{"id":"1","contextID":"1","name":"Living Room","image":"18"},
{"id":"3","contextID":"1","name":"Toilet","image":"75"}]}
I am then performing this code:
resultArray = new JSONArray (data);
and returning this JSONArray. However, I get a JSONException error:
JSONObject cannot be converted to JSONArray
Surely this is a JSONArray not a JSONObject? Or is it a JSONObject of JSONObjects? I'm pretty new to JSON and I'm wanting to loop through and create new Locations using these imported values. Is there an easy or established way of doing this?
Many Thanks.
Data is a JSONObject, and Data["result"] is a JSONArray that contains JSONObjects.
Its a json object with a JSONArray of JSONObjects inside of it. { } means object and [] means array. So you get the top level string as a JSON object, then get the results parameter as an array, then get each index into the results as an object (and you can get the parameters of those via getString, etc).
Data is actually a JSONObject that contains a JSONArray named "result." If you wanted to get the JSONArray you'd have to do the following:
JSONObject dataObj = new JSONObject(data);
JSONArray dataArr = dataObj.getJSONArray("result");
For future reference, since you're new to JSON, data inside {} braces is a JSONObject and data inside [] braces is a JSONArray. Arrays and objects can be nested inside of each other and it's sometimes hard to read. I recommend formatting your data if you need help reading it. I personally use http://jsonformatter.curiousconcept.com/ to format and validate my data. I'm not associated with the site in any way. I just find it really useful.

It isn't a JSONObject. It isn't a JSONArray. What is it?

I have not been working with JSON very long. I have the following response and I'm struggling to understand how to call the details of the "Topic". I thought it was a JSONObject, but Android's logcat is telling me JSONObject["Topic"] not found.
[{"Id":1,"TopicId":1,"UserGuid":"C214ED74-07A7-409E-84FF-AF0457CF581A","Topic":{"Id":1,"AdminUserGuid":"C214ED74-07A7-409E-84FF-AF0457CF581A","Title":"Test Topic 1","AccessType":"public"}}]
Any help is greatly appreciated.
This is a JSONArray with one element, a JSONObject with multiple properties, one of which is a JSONObject named topic:
JSONArray posts = new JSONArray(myJsonString);
JSONObject post = posts.getJSONObject(0);
JSONObject topic = post.getJSONObject("Topic");
Use JSONLint to indent your JSON string this way you can understand the structure better
It's a JSONArray with one object in which there are 4 objects and one of them has 4 attributes.

Categories

Resources