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".
Related
Lets assume I have a GET request that returns something like the following:
[
{
"id": 1,
"name": "Mark"
},
{
"id": 2,
"name": "Steve"
},
{
"id": 3,
"name": "Bill"
}
]
How can I return the wanted object from a List? or something that contains maybe this JSON as a String or what is the correct approach to get only one of the items from the response for example lets say i need to get Bills info only so i want to parse that JSON to get only this:
{
"id": 3,
"name": "Bill"
}
And no, I do not want to do this parsing in the GET request URL. I need to be able to get it from the list of everything that the GET request returns.
"$[2]"
In JsonPath, $ represents the anonymous root of the queried JSON, for cases like this one when you need to refer to it directly instead of stuff like "stuff.things[8]"
In this case, the array you're trying to analyze is the anonymous root, so you refer to it as $. Then you want the element at index 2 of this array, so it's $[2]
I did another solution that actually fits exactly for my needs. I deserialized the JSON response into a List of POJO classes that the JSON body corresponds like this:
List<MyEntity> myList = new ArrayList<>();
myList = given().
contentType(ContentType.JSON).
when().
get(getURL).
then().
extract().
body().
jsonPath().
getList(".", MyEntity.class);
This way I get a List of the initialized MyEntity classes and I can just do anything I need to, for example I just modify the values like this:
myList.get(0).setName("newName");
Then I can just send them back with a POST/PUT calls or something like that. Works like a charm!
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
}
}
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 have this JSON:
{
"header":
{
"IssuerID": "000141",
"AuthenticationID": "e07020c0d040a050a0808099",
"AuthenticationDateTime": "20151103093035",
"AuthenticationDateTimeGMT": "20151103093035",
"Signature": "MThEMTExQkMzQzM0OUIxQjM5MDc2MjFGMzMyQjhDNTk1OTI0NDNERTg5ODcwQjNFOTc0ODQwNThBNkQxNTgzNTk2N0YzN0I2OTkyMzI1QjY2OENDQjgxRUNERDlGNDFDNzVCMzQ5Njg5NTY4NzkwNUQ5MzBDN0ExOTVGOUY0OUY2QjlCQzlDQkREOEQ3NjEzRkQ2OEYyMDhEQTY2QTkzNUZDM0UzOTI3RDk2OTYwODg4NTkyNzYyQUJCQkJFREZGNzNCNEEyNUU5OTc5OTFFODk2MTQ0Q0Y4Q0RGNzg1M0JBQTM4QkZBQzRFRUY2MTkzM0E4REI3QkQ0MEJBRkU4OTlEOTVDNTkxOTQ0M0IwNjMyMzZDQ0U4MzdBQTQzODU3RkMyOEQ0Rjk2NUMyRkNERUM0NDREQkIzNUM0QUVERDUzRjFBOTk5RTQ4Mjk4MzNERjU3RTQ1QUE2Nzc4MDUyRTdERTdGRTVFRURGRkVGMTlFN0Y2QTAyQTVCNjk3NUU2OUNGRUU3MzRGNDZDOTE0Q0U3NTk5NzdGNDkyOTdFQkRGREIwNDBCNDhBQTkzMzE1QjU0MzI1Njk0MjgxMjVDMzM5OUM3MTExNTg4NENBOTU3QTM4OTU5MTY5OTQ1NkQ2NDNFOUVEMjU5MjRDNzhEMDQxMEJGM0ZEQUVFM0Y1QTU="
},
"body":
{
"TransactionDateTime": "0151103093035",
"TransactionID": " SP020110216",
"IASauthenticationRequestReferenceID": "h0IrqhqBoUpUCiSv17NB0vHvABIUxHGCurJZFzUWdZJz9TxYio",
"VerificationID": "h0IrqhqBoUpUCiSv17NB0vHvABIUxHGCurJZFzUWdZJz9TxYio ",
"Acquirer_id": "000014",
"MerchantName": " Twin Hotel ",
"CurrencyCodeISO": "360",
"Amount": "970000.00",
"CardNumber": " BmaHLuFRg4SaPnaGB07t5fNrHXr/lyOa ",
"AuthenticationResponseCode": "00",
"AuthenticationResponseDetails": "Success",
"ValidityDateTimeExpireGMT": "20151103094035",
"Expiry_Period": "10"
}
}
How can I validate this json? For example, issuer id must be integer and have min and max values and if someone put headers instead of header it can get result: "json not valid".
I'm using java and json.org.simple for parsing.
Can anyone help me?
If you are looking for real schema validation you might want to have a look at http://json-schema.org/. There are validators for most common languages.
Assuming there are classes to represent the above structure you could try to use Java Bean Validation.
In your case, I would use a deserializer like jackson and not a json-schema, since you seem to have integer and dates encoded as string in your json. Thus, in a json-schema you would need to define strange regex. To see how to use jackson and to weigh the pros and cons of each method you can take a look a my blog post here: Three Ways to Validate JSON in Java
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.