JSON Array or Object Error in Android - 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.

Related

Json Object: linked list?

I have a Json string:
String json = "{\"I\":0,\"lst\":[{\"i1\":100500,\"s1\":\"abrakadabra\",
\"aList\":[{\"text\":\"secret will of my Dad\"}]}]}";
JSONObject o = new JSONObject(json);
My question: how, using Json Obj methods, to browse through each node element recursively?
Vitali, I don't have enough reputation points to reply to your comment, so posting it as an answer. In that post I linked, I meant the code snippet with loopThroughJson() method. I haven't tried it myself but that looks right. For completeness, this is the link again -
Recursively parsing JSON via JSONObject to fetch value against specific keys
Loop through the object, get child as reference of Object class using the get() method, if that object is instance of JSONObject or JSONArray, go deeper.

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

How do I turn a JsonElement into Json without the members tag?

I have a method that parses the differences between two JsonElements and then returns a JsonElement that represents an object containing only the differences between the two elements.
I am then attempting to send the returned JsonElement via API PUT request and generically parse the response to an object type. The problem is that JsonElements parse to Json with the members tag in front of all of its contents.
For Example:
{"members":{"id":1172327,"assets":[{"id":436379,"licenseState":"MI","odometer":"12345"}]}}
How can I remove the members tag from the JsonElement. I would prefer not to do it manually. I tried JsonElement.getAsJsonObject() and that fails. I also attempted to get the JsonElement as a JsonArray (JsonElement.getAsJsonArray().get(0)) but this failed because the JsonElement is not a JsonArray.
import org.json.JSONObject;
/** Assuming json_string is your json string **/
JSONObject jsonObj = new JSONObject(json_string);
JSONObject jsonMembers = jsonObj.getJSONObject("members");
//will return "{"id":1172327,"assets":[{"id":436379,"licenseState":"MI","odometer":"12345"}]}"
Log.d("Members only:",String.valueOf(jsonMembers));
Note: Make sure to surround with try/catch in case it's not valid json!!
Hopefully this is what you're looking for.
What if you just do JsonElement.getJSONObject("members") ? That will grab the element with the key "members"

How to decode an array of array elements in Android

A PHP script is sending to an Android app some data in the following format
[{"event_id":"4","message":"test"},["person1","person2"]]
I want to exact the 2 elements from this array into other arrays so I can easily manipulate the data. I got to the point in which the above response from the server is being converted into as string. What I can't seem to be able to do is to parse the data into arrays. I'm trying something on the following lines:
receivedData = new JSONArray(result); //result is the string response from the server
JSONArray array1= receivedData.getJSONArray(0);
JSONArray array2= receivedData.getJSONArray(1);
int len = array1.length();
but lenis not giving me back anything :(
What am I doing wrong and how could I change it.
Many thanks
What if you start by invoking new JSONObject(result); and then pulling an array out of that? I suspect you're trying to pull an array out of something that is not an array. Your PHP should not return something wrapped in [ ] it should return it wrapped in { }... also I believe your third JSON element (the array itself) is just hanging about without a label, which I believe is illegal.
so...
if your php produced this:
{"event_id":"4","message":"test"},"people": ["person1","person2"]}
and your java was this:
JSONObject j = new JSONObject(result);
String [] people = j.getJSONArray("people");
I believe you'd have what you are after.

Converting arraylist of custom class to JSONArray

I didn't expect this is that complex. But I can't figure out how I can convert my arraylist of custom class to a JSONArray. I understand there is no direct method to do that. So I made arraylist of JSONObjects from my arraylist. Now in order to save this into a JSON file, how can I convert the arraylist of JSONObjects to JSONArray?
Like this:
JSONArray toReturn = new JSONArray();
for(JSONObject object : yourJSONArrayList){
toReturn.put(object);
}
toReturn will then be a JSONArray that has all the JSONObjects from your arraylist of JSONObjects in it.
Give Gson Library a try, all that custom json conversion code goes away.

Categories

Resources