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
Related
I got JSON file like this:
{
"issues": [
{
"no1": 5509,
"date": 1451520000
},
{
"no1": 6713,
"date": 1451433600
}],
"no2": [
220380,
163950,
213330,
215250,
174300]
}
I need to create a map issues where the no1 value will be key of the map and date value will be a value of the map. I've got already method which transfers JSON to map from file, and I know how to get the issues which will be: mapFromJson.get("issues"); what I get is:
issues=[{ no1: 5509.0, date: 1.45152E9}, {no1: 6713.0, date: 1.4514336E9}]
How to convert this to map?
You can convert to JSON using JSON Library (you must to attach JAR file in your project). Also, I found a good answer for convert JSON to Map in this link. I recommended to use these functions.
Example:
JSONObject json = new JSONObject(<your_json_string>);
ArrayList issues = (ArrayList) jsonToMap(json).get("issues");
Each element in the ArrayList issues, it's already HashMap. For example, if you want to get date of no1, you could access of this way:
((HashMap)issues.get(0)).get("date")
Suppose that I serialise two different objects and save them to a directory.
Problem: Upon application start up, parsing the JSON files are not a problem - since GSON is employed, I can write my own serialisers and deserialisers for both of the JSON files for their respective objects to be constructed.
But the problem is, how can I differentiate between the numerous JSON files in terms of what they store within them, so I can apply the correct deserialiser to it.
Thank you, best.
Consider standardizing your JSON structure to include document type. You can even store the target object type in that field. Good practice is to include document version number as well. Example below shows two different versions of the 'account' document and a transaction document. All three can be stored in, say, the same Couchbase bucket. The way to differentiate between different documents would be to look at the "doc_type" field and the document version (if required). From the GSON serializer selection standpoint, you can look at at the "doc_type" in a switch/if-else statement or store the target object type in place of "account" or "transaction" and then, at the expense of performance, dynamically parse JSON to POJO.
{
"doc_type": "account",
"doc_ver": 1,
"content": {
"accnt_no": "12321645645484",
"name": "Name or alias",
"email": "Email address",
"password": "Password in raw format",
"exp_date": "06/10/2017"
}
}
{
"doc_type": "account",
"doc_ver": 2,
"content": {
"accnt_no": "12321645645484",
"name": "customer name",
"email": "customer email",
"password": "pass",
"timezone": "customer timezone",
"ip": "IP address",
"spoken_languages": [ "EN", "RU" ],
"exp_date": "06/10/2017"
}
}
{
"doc_type": "transaction",
"doc_ver": 1,
"content": {
"accnt_no": "12321645645484",
"tran_date": "06/04/2017",
"tran_time": "09:15:84.953"
}
}
Hope this helps.
I think that the best way is parse JSON to a HashMap<String, Object> with multiple level. GSON will parse your JSON to HashMap with key is object name and value is an object (This object will belong to 3 type: HashMap for a object in JSON, List for an array in JSON and String for a string in JSON). To using this HashMap you need to iterate through the HashMap using a recursive method.
I want to create a JSonObject with some values for call a webservice but where webservice in a order like:
{
"id" : 1
"email" : "test#test.com",
"pin" : 1234,
"age" : 25,
"firstName" : "Test First Name",
"lastName" : "Test Last Name",
"location" : "India",
"phone" : "1234567890"
}
but when I create a json object from android code it is not maintaining the order like:
requestJOB=new JSONObject();
requestJOB.put("userid",Pref.getValue(this, Const.USER_ID, requestJOB.optString("userid")));
requestJOB.put("email", Pref.getValue(this, Const.PREF_EMAIL, requestJOB.optString("email")));
requestJOB.put("pin", Pref.getValue(this, Const.PREF_PIN, requestJOB.optString("pin")));
requestJOB.put("age", Pref.getValue(this, Const.PREF_AGE, requestJOB.optString("age")));
requestJOB.put("firstname", etFirstName.getText().toString().trim());
requestJOB.put("lastname", etLastName.getText().toString().trim());
requestJOB.put("phone", etPhone.getText().toString().trim());
requestJOB.put("location", etLocation.getText().toString().trim());
I write the code my desired order but JsonObject change the order in run time. I also tried with map and LinkedList but A exception is
occured when I want to convert LIST to JsonObject.
I searched in stackoverflow where no satisfactory answer.
In this situation I don't understand exactly what I have to do.
In Android platform there is better way to serialize a object in json by using Google GSON API... Which provide all possible functionality to convert a class to their corresponding JSON. U can prepare nested jsonobject ..
Nested like json object with in a json object. Json array embedded within a json. Object
Multiple jsonarray with in a same json object. And their may be multiple variety .. Just explore this jar .. It's very easy to use and user-friendly jar. Just go and grab it .. Hopefully u feel better with this API
I used this jar in my Android project actually
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'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.