Json Object: linked list? - android

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.

Related

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"

Adding link to json object in android

JSONArray albumarray=new JSONArray();
JSONObject imgobj=new JSONObject();
imgobj.put("thumb", filepath.get(i));
imgobj.put("main", filepath.get(i));
albumarray.put(imgobj);
JSONObject albumjson=new JSONObject();
albumjson.put(albumname,albumarray);
When I convert albumjson to string using
albumjson.toString()
I am getting output as below.
{\"test2\":\"[{\\\"thumb\\\":\\\"http:\\\\\\/\\\\\\/dev.mysite.in\\\\\\/mysite\\\\\\/sites\\\\\\/default\\\\\\/files\\\\\\/512da541b31fe.jpg\\\",\\\"main\\\":\\\"http:\\\\\\/\\\\\\/dev.mysite.in\\\\\\/mysite\\\\\\/sites\\\\\\/default\\\\\\/files\\\\\\/512da541b31fe.jpg\\\"}]\"}
the correct format i need is
{"test2":[{"thumb":"http://dev.mysite.in/mysite/sites/default/files/512d9bdced1f2.jpg","main":"http://dev.mysite.in/mysite/sites/default/files/512d9bdced1f2.jpg"},{"thumb":"http://dev.mysite.in/mysite/sites/default/files/512d9be134cb8.jpg","main":"http://dev.mysite.in/mysite/sites/default/files/512d9be134cb8.jpg"}]}
How to replace additional slashes.
PLease use JSONObject.getString('keyName') method instead of toString()
EDIT:
You should first understand why those extra \\ are showing up.It is an escape character for ".Hence,it is very much required there and is a part of JSON encoding .Hence,one should always use the above method to get values of keys whenever needed.
apart from that you can try :
JSONObject.toString(4) where 4 is actually indent spaces and see whether it helps.Otherwise there's simply no other option than to replace those extra \\ like
myJsonString.replaceAll("\\","");
or
myJsonString=myJsonString.replaceAll("\\\\","");
SECOND EDIT:
The string you are sending is perfect to send to any server.You need to decode that string at the server end to JSON and then utilise it.
If you are using .NET you can see this. Or if you are on some other platform you need to find out how to decode to JSON on that platform.
There are two things going on here:
Your tools are confusing you. When it shows the output:
"{\"test2\":\"[{\\\"thumb\\\":\\\"http:\\\\\\/\\\\\\/dev.lrcdn.in\\\\\\/shiaspark\\\\\\/sites\\\\\\/default\\\\\\/files\\\\\\/512da541b31fe.jpg\\\",\\\"main\\\":\\\"http:\\\\\\/\\\\\\/dev.lrcdn.in\\\\\\/shiaspark\\\\\\/sites\\\\\\/default\\\\\\/files\\\\\\/512da541b31fe.jpg\\\"}]\"}"
It is telling you that the result is a string containing:
{"test2":"[{\"thumb\":\"http:\\\/\\\/dev.lrcdn.in\\\/shiaspark\\\/sites\\\/default\\\/files\\\/512da541b31fe.jpg\",\"main\":\"http:\\\/\\\/dev.lrcdn.in\\\/shiaspark\\\/sites\\\/default\\\/files\\\/512da541b31fe.jpg\"}]"}
Taking that string and formatting it:
{"test2":
"[{\"thumb\":\"http:\\\/\\\/dev.lrcdn.in\\\/shiaspark\\\/sites\\\/default\\\/files\\\/512da541b31fe.jpg\",\"main\":\"http:\\\/\\\/dev.lrcdn.in\\\/shiaspark\\\/sites\\\/default\\\/files\\\/512da541b31fe.jpg\"}]"
}
We can see that you've constructed a json object containing a json-encoded string, rather than a nested jsonobject. For whatever reason, your code is having the effect of:
JSONArray albumarray=new JSONArray();
JSONObject imgobj=new JSONObject();
imgobj.put("thumb", filepath.get(i));
imgobj.put("main", filepath.get(i));
albumarray.put(imgobj);
JSONObject albumjson = new JSONObject();
albumjson.put(albumname, albumarray.toString());
That sounds like a bug in your json library

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.

Accessing an object from JSON in Android

I have a question that I am a little bit confused about. I am quite new to JSON and getting JSON values in the android API. I am trying to access an array within the response I get. the JSON code I am getting is something like this:
Response:
{
"event": {
"participants": []
},
"status": "success"
}
How would I access the participants array and store their values. This is what I am trying at the moment... but I dont appear to be getting what I want.
try{
//get the JSON values from the URL.
JSONObject json = jParser.getJSONFromUrl("http://somesite.com/api/find?"+"somevar="+someJavaStringVar);
json_event = json.getJSONObject("event");
JSONArray json_array_participants = json_event.getJSONArray("participants");
} catch(JSONException e) {
}
The thing I am mostly confused about is... what is the arrays type equivalent to. Any advice or reasoning as to the correct way to get ahold of that variables value would be great... thanks guys.. :).
Think JSON is really just a key-value pairing. The JSONArray type is just an array full of objects (like Object[]) - it has no idea what the objects it contains are or what they're to be used for. Its up to you to assign meaning to the JSON stream based on what you know of the source. From what I see of your code, most of it looks fine, though I don't know what your jParser.getJSONFromURL() is doing. Typically, you would build the JSON from the response string like so:
String jsonString = getJSONFromUrl("http://somesite.com/api/find?"+"somevar="+someJavaStringVar);
JSONObject json = new JSONObject(jsonString)
JSONObject json_event = json.getJSONObject("event");
JSONArray json_array_participants = json_event.getJSONArray("participants");
You can iterate through the array like any other array to get subobjects or whatever:
for(int i=0; i < json_array_participants.getLength(); i++) {
JSONObject participant = json_array_participants.getJSONObject(i);
// Do stuff
}
As a side note - I WOULDN'T use GSON until you understand the underlying protocol, at least a little - because you never know when you might want to parse your JSON from a different language for some reason.
I would strongly recommend to use gson instead as your preferred parser since it will do all the job of serializing and deserializing for you except creating the domain objects.
This tutorial should get you going:
http://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html
This will depend on what the server is supposed to return. It could be an array of anything and if this is a public service, there should be a specification to go off of.
If you are in charge of the server portion as well, and you have a backing object, Google's GSON library is extremely easy to use. It will also keep type information straight.

Categories

Resources