I've worked with several different APIs where I needed to parse JSON. And in all cases the Response is constructed a bit differently.
I now need to expose some data via a JSON API and want to know the proper way to deliver that Response.
Here is an example of what I have now, however some users (one using Java) are having difficulty parsing.
{"status": "200 OK",
"code": "\/api\/status\/ok",
"result": {
"publishers": ["Asmodee", "HOBBITY.eu", "Kaissa Chess & Games"],
"playing_time": 30, "description": "2010 Spiel des Jahres WinnerOne player is the storyteller for the turn. He looks at the 6 images in his hand. From one of these, he makes up a sentence and says it out loud (without showing the card to the other players).The other players select amongst their 6 images the one that best matches the sentence made up by the storyteller.Then, each of them gives their selected card to the storyteller, without showing it to the others. The storyteller shuffles his card with all the received cards. ",
"expansions": ["Dixit 2", "Dixit 2: \"Gift\" Promo Card", "Dixit 2: The American Promo Card", "Dixit Odyssey"],
"age": 8,
"min_players": 3,
"mid": "\/m\/0cn_gq3",
"max_players": null,
"designers": ["Jean-Louis Roubira"],
"year_published": 2008,
"name": "Dixit"
}
}
The Java user in particular is complaining that they get the error:
org.json.JSONException:[json string] of type org.json.JSONObject cannot be converted to JSONArray
But in Python I am able to take in this Response, fetch "result" and then parse as I would any other JSON data.
* UPDATE *
I passed both my JSON and Twitter's timeline JSON to JSONLint. Both are valid. The Java user can parse Twitter's JSON but not mine. What I noticed with Twitter's JSON is that it's encapsulated with brackets [], signifying an array. And the error this user is getting with my JSON is that it cannot be converted to a JSON array. I didn't think I need to encapsulate in brackets.
It looks valid according to http://json.parser.online.fr/ (random json parser). Its in the other code i'd say ;)
How exactly are you generating this response? Are you doing it yourself?
I see you have a dangling comma at the end of the last element in publishers (i.e. after the value Kaissa Chess & Games).
I'd recommend using JSONLint to ensure your JSON is valid.
Related
The return from an external application is an Input Stream that looks like this:
JSONObj = {
"output":
[
{
"box":[0, 44, 43, 189],
"text":"~9 000 -"
}
]
}
I'm having trouble parsing the JSON in Java
The 'JSONOBJ' keeps coming back as an Invalid Token.
Is there a way to simply begin parsing at the '['?
I would advice against manipulating the JSON prior to parsing it. If you want to cut out parts it's a sign that your target data structure (the Java class you're intending to get) does not match the data you're receiving. These two should be in sync.
Throwing this into any decent JSON parser will tell you that this is invalid JSON.
Particularily, at line 6, you should remove the manual line breaks, since JSON only permits explicit ones using the line seperator \n:
{
"output": [
{
"box": [
0,
44,
43,
189
],
"text": "~9 000 -"
}
]
}
The easiest way might be:
json = json.substring(json.indexOf('{'))
And I actually disagree with Nicktar's statement, since that external program isn't even returning valid JSON (and I'd consider it a very very stupid implementation to be frank). There is no need in saying "hey, that's an object" because that's actually implicit. If a JSON starts with {, it's an object, if it starts with [, it's an array.
I'm looking to dump, rather toString() a section of JSON that I want to store locally as a string, since it it is highly variable and not imperative for me to know the contents.
I'm using JsonReader for the parsing:
https://developer.android.com/reference/android/util/JsonReader.html
Unfortunately, when I reach the token that contains what I want to dump, JsonReader does not have a method for dumping the entire JSON to a string.
This is the closest that it has:
https://developer.android.com/reference/android/util/JsonReader.html#toString()
It seems that I may have to use regex to pull out the value of the token I am targeting.
Is there another, better solution? How would I do this with regex?
Assume that this is the sample JSON and I am targeting the user key:
{
"id": 912345678901,
"text": "How do I read JSON on Android?",
"geo": null,
"user": {
"name": "android_newb",
"followers_count": 41
}
}
ya i know that it's very usual problem while mapping but my problem is some different hear is the scenario
when my response have the data it gives me JSON Response like this
{
"responseID": "110",
"resultSet": [
{
"USERNAME": "Aninja",
"position": "Developer",
"salary": "60000"
}
],
"isSuccessful": true,
"rtnCode": "0000"
}
and below is the same JSON response when data is not found
{
"responseID": "123",
"resultSet": {},
"isSuccessful": true,
"rtnCode": " "
}
as i can see hear when response have some data result set have JSON Array but when no data found we have JSON Object as a response
so this is the reason I'm getting this problem.
so my question is that how should i handle this problem thanks for your response
Edit: the main problem is that i have made my model like list of JSON Object it works fine when there is result but it gives me error Can't convert JSON Object to JSON Array when result is empty s please suggest me how can i hanle it I'm using Jackson 2.2 i have also tried #JsonInclude(Include.NON_EMPTY) and #JsonInclude(Include.NON_NULL)
I wouldn't say it is mistake from server or back-end. But it is always a good practice to provide appropriate "Null Object Pattern" which describes the uses of such objects and their behavior.
So for better practice array which doesn't have any values should be sent back using "[]". So in this case "resultSet" should be given as [] instead of {} so it can be easily understood at front-end.
There are number of examples here which shows why it is useful to follow Null Object Pattern.
For example, if you are returning count in you response and there is no count then it is better to use "0" instead of "null".
I have a string response like below which is a invalid json as it contains "obj13=".I want to convert it to a JSONObject(JAVA) and use it.Is there any good way to convert it to JSONObject without using String split operation.
obj13={
players: [
{
name: "rocky",
place: "brazil",
age: "21",
},
{
name: "andy",
place: "New Zealand",
age: "23",
}
]
}
This is, of course, JavaScript, not JSON. If you can, I would go back to the service provider and ask for a JSON response.
If the format of the string is consistent, you could just use:
json=json.substring(json.indexof('=')+1);
and then parse the result. Note that most good parsers should have an option to allow the keywords without quotes and to allow the extraneous commas (mine does, but unfortunately for you it doesn't create JSONObject's but is of a lower level - it's designed to construct the data-structure of the caller's choice, which could be a JSONObject if that's what you wanted but you'd have to code it).
If the result may or may not have the assignment, you may want to get a bit fancier and ensure that the non-whitespace characters before the '=' are valid for a JS identifier and the first non-whitespace after it is '{'.
i am using google custom search engine and getting the results in JSON format.for certain queries,the JSON result has duplicate keys and hence it produces a JSONException: Duplicate key "nickname" etc..
i am using JAVA.
String str=//contains the query result in json format
JSONObject ob=new JSONObject(str) produces the exception
may know how to resolve this exception?
here is the JSON reply:
{
"kind": "customsearch#result",
"title": "The World Factbook: India - CIA - The World Factbook",
"htmlTitle": "The World Factbook: \u003cb\u003eIndia\u003c/b\u003e -",
"link": "https://www.cia.gov/library/publications/the-world-factbook/geos/in.html",
"displayLink": "www.cia.gov",
"snippet": "Jan 20, 2011 ... Features a map and brief descriptions of geography",
"htmlSnippet": "Jan 20, 2011 \u003",
"cacheid": "0n2U45w_dvkJ",
"pagemap": {
"metatags": [
{
"il.secur.classif": "UNCLASSIFIED",
"il.title": "(U) CIA The World Factbook",
"il.summary": "CIA - The World Factbook",
"il.cutdate": "20040101",
"il.secur.classif": "UNCLASSIFIED",
"il.title": "(U) CIA The World Factbook",
"il.cutdate": "20040101",
"il.secur.classif": "UNCLASSIFIED",
"il.pubdate": "20040101",
"il.postdate": "20040501",
"il.cutdate": "20040101"
}
]
}
}
here il.secur.classif occurs multiple times
JSon object, like any other object, can not have two attribute with same name. That's illegal in the same way as having same key twice in a map.
JSONObject would throw an exception if you have two keys with same name in one object. You may want to alter your object so that keys are not repeated under same object. Probably consider nickname as an array.
You need to paste the JSON object in the question.
If you really need this functionality, roll back to gson 1.6. Duplicate keys are allowed in that version.
You can make use of the Jackson library to parse JSON. I'd problems doing the same task as you with org.json's package, but I turned to Jackson and I solved it: http://wiki.fasterxml.com/JacksonHome