I am having trouble with some basic JSON parsing - java

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.

Related

Get a dump of a section (object) of JSON

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
}
}

Jmeter POST API issue

There is a JAVA REST API (Put request) that I want to hit with values from a CSV file.
The CSV file is:
The JMETER CSV configuration is:
This is how I have set up the JMETER Configuration to hit the API:
The deserialisation on the Java side is not happening correctly. From POSTMAN, the following works:
{
"productId": "ABC",
"score": 4.42489
}
Why is the Jmeter POST configuration not working correctly?
Error: Received Unknown exception com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not construct instance of double from String value '$score': not a valid Double value
Update: On doing this in Jmeter configuration:
{
"productId" : "${product}",
"score": "${score}"
}
I got the following error:
Received Unknown exception com.fasterxml.jackson.core.JsonParseException: Unexpected character ('T' (code 84)): was expecting comma to separate OBJECT entries at [Source: java.io.PushbackInputStream#4063ce7d; line: 2, column: 18] Similarly for M, M and R. So 4 errors in total.
Update 2:[Solved]The following CSV Data Set Configuration worked without any change in the actual CSV file!!
A Big Thank you to #user7294900 for the help!!
i do wonder if you might also have a problem with product_id being the parameter name versus productID that works directly in postman.
You forgot curly braces (this is not velocity/postman)
You need to send HTTP Request Body Data:
{
"productId": "${product}",
"score": "${score}"
}
Check the maunual for more details:
Variables are referenced as follows:
${VARIABLE}
Also your quotes in CSV file is redundant, either change Allow quoted data to true or better yet remove all quotes " from CSV file.
You don't need quotation marks around "${product}" and ${score} as:
Your CSV file already has quotations around ProductId I don't think you need duplicate ones
Your application expects a Double and you are basically sending a String
So change your payload to look like:
{
"productId" : ${product},
"score": ${score}
}
More information:
JSON Data Types
REST API Testing - How to Do it Right

JSON Object can't be converted to JSON Array

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".

How to convert Invalid JSON String to JSONObject in Java?

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 '{'.

What is the proper format for a JSON Response?

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.

Categories