JSONObject jObject = new JSONObject(myJsonContent);
JSONObject menuObject = jObject.getJSONObject(String.valueOf(jObject.keys().next()));
myJsonContent is response from server
and i dont know what is start tag ... and i dont want to know even...
and after that without knowing any tag of response i want to parse response..
this is requirment because in the future we will not be knowing if server guys change data and tags as well so we need to create like this which will be work even if server guys changes all the tags in future
please help me any kind of help is very appriciable
You should check here,
http://developer.android.com/reference/org/json/JSONObject.html
get keys from json object i.e. iterator and loop thorough it and use jsonObject.names() to get the array of names. This should guide you to the right solution.
Sorry for the plug, but you could try do what I did - use this parsing object generator
Related
I had error
org.json.JSONException: No value for data
image
I had tried many ways but I can't solve it. Please help me to fix it.
It is possible to use Gson API to parse JsonObject above to java Object?
You need to get posts before.
JSONArray data = responde.getJSONObject("posts").getJSONArray("data");
instead of
JSONArray data = responde.getJSONObject().getJSONArray("data");
This should work for this scenario, but you really need to check for non existent keys or values.
I'm currently deveolping an Android application that has Django framework as it's server side.
When i'm posting a data of a new user to my database i am POSTing a multipart request that has a user part inside.
The user for some reason is represented as a list but when i take it out of the request.data['user'] it's a str instance (Yea i dont know why...)
When i fetch that str i started working on it with json package.
I looked up on the internet (to many places..) how to convert a string in json format to a dictionary.
What i found is that when you use the json.loads command it doesn't give a dict back but a str instance :)
This is the code on my server side when i enter the create function of the ModelViewSet that handles the creation of the user.
userJson = request.data['user']
userJson = json.dumps(userJson)
userJson = json.loads(userJson)
What i tried to do is to make a string of my own in JSON format and that called the json.loads() command which gave me the dict object..
There seems to be a problem with processing the str from the http request of django rest framework for some reason or there's something else i am not seeing.
I tried the following links -
Converting JSON String to Dictionary Not List
http://docs.python-guide.org/en/latest/scenarios/json/
Didn't worked also..
Now, i tried accessing the str i got from json.loads() like a dictionary in this way.
id = userJson['id']
Now lets say maybe i passed a wrong json format to the loads function, it should have thrown an exception..
The code above (getting the id) raised an exception of 'String indices must be integer' - it doesn't convert it to dict! LOL xD
Good note worth mentioning - I'm trying to convert the json to a dictionary so i could access it like this - dictObject['id']
Well i would really appreciate every help!
Thanks :)
For some reason , when i did this commands-
userJson = request.data['user']
userJson = json.loads(userJson)
userJson = json.loads(userJson)
What i got to have inside the userJson after the second json.loads(userJson) I got the actual dict object to the userJson member.
Appearently it is a bug.
21 January - another update, I truly was doing double Json encoding on the Android application so that was the reason for double json. loads()
i have a running app but i had a little problem with my sever,i have yet to solve my server problems and i'm encountering this problem with my log in the error comes from the authentication method.the error says jsonarray cannot be converted to jsonobject i've made a pastbin of my log and i was hoping someone can take a look at it and tell what my problem is.i think my problem is that i cant access my database but im not really sure if its the problem or my problem is my json.i cant hink of way to authenticate my username and password withour having problem like "at org.json.JSON.typeMismatch(JSON.java:111)" here is my paste bin http://pastebin.com/zgzbxcSV
you get from the server a (maybe empty) json array and you are try to convert it in a JsonObject.
instead of
JSONObject obj = new JSONObject(string);
you should do
JSONArray obj = new JSONArray(string);
You are trying to convert JsonObject to JsonArray so getting error.
You have to convert proper jsonObject to another object as per your requirement.
You can find useful demo with explanation.
If you find and trouble for parsing your json after researching this demo then let me know.
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
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.