Rest assured and Java: how to get wanted JSON object/body? - java

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!

Related

How to get the name of array in JSON using Java

Given a Json object or a Json array that contains a Json array inside, I need to return the name of the array itself, without specifying the value inside the array.
In the code, given JSON, and Jsonpath from user, I need to return the name of the array.
Example- given this JSON:
{
"Contract details": [
{
"type": "regular",
"Details": [
{
"Name": "Josh",
"Country": "USA"
},
{
"Name": "Jake",
"Country": "UK"
}
]
}
]
}
I want to be able to find if the array block "Details" exists within the JSON.
Right now, in order to verify its existence, the user need to specify the full Jsonpath to a value inside the block, which is time consuming, like this:
$.Contract details[0].Details[?(#.Name== 'Josh')]
This is where I get the jsonPath result in the code, and where I want to verify afterwards the existence of the array object.
//json and jsonPath are given strings
Object jsonObjectType = JsonPath.read(json, jsonPath);
I want to verify that "Details" array block exists, maybe by a short effective JsonPath, or some other way in the code, given json as string.

Spring Response to Java Object when Json KEY keeps changing

I am calling an external rest-API from my spring boot code which returns JSON something like this.
{
"Jack": {
"employeeId": 1,
"active": 1,
"hours": 40
},
"Ryan": {
"employeeId": 2,
"active": 1,
"hours": 40
},
"Ken": {
"employeeId": 3,
"active": 1,
"hours": 40
}
}
I am trying to convert this to java pojo using jackson and using RestTemplate to call this
I am not sure how to create java class for something like this, as the employee name keeps changing and there is No "Name key" in JSON. I can create a class for the fields employeeid,active and hours but now sure how to accommodate the employee name
Is there a way to convert these to java objects
The best way is to change the API response like "name":"Jack".It seems that it is not a good json form, isn't it?
But if you can do this,maybe this question will not exists.
The other way to convert is to convert is as Map<String,Object> and then you can get key set and you can handle the object as usual json.

Mapping JSON Array to Java POJO

How would i map this JSON to an object?
{"d":"[{\"Key\":\"3\",\"ExternalKey\":\"143234A\",\"Name\":\"cup of juice\",\"Litres\":\"2 litres\",\"Date\":\"2016-10-06T08:32:27\",\"Capacity\":5.4900,\"CapacityType\":\"%\"}, {\"Key\":\"3\",\"ExternalKey\":\"143234A\",\"Name\":\"cup of milk\",\"Litres\":\"2.4 litres\",\"Date\":\"2016-10-06T08:32:27\",\"Capacity\":1667.6100,\"CapacityType\":\"M\"}]"}
I've tried using a HashMap but it just puts "d" as the string and the rest as a String object with one element
This is an extremely common problem known as data marshaling. In java, Jackson is the general best solution. Read this tutorial: http://wiki.fasterxml.com/JacksonInFiveMinutes
Your Json string has some extra " characters.
This is the final json:
{
"d": [
{
"Key": "3",
"ExternalKey": "143234A",
"Name": "cup of juice",
"Litres": "2 litres",
"Date": "2016-10-06T08:32:27",
"Capacity": 5.49,
"CapacityType": "%"
},
{
"Key": "3",
"ExternalKey": "143234A",
"Name": "cup of milk",
"Litres": "2.4 litres",
"Date": "2016-10-06T08:32:27",
"Capacity": 1667.61,
"CapacityType": "M"
}
]
}
Now you can copy the json and paste it here to get the pojo.
There are n numbers of libraries available for parsing the JSON and convert into in java classes.
Some of the examples are,
GSON
Jackson
Logan Square
Moshi, etc
You need to create a java class which map with your JSON Response and need to change your pojo according to parsing library.
For Example,
Using Logan Square you must annotate your POJO class to #JsonObject and all properties must be annotated with #JsonField.
Now, you can parse your json using method
...
LoganSquare.parse(jsonString, pojoClassName);
...
Hopefully this will help you.
Cheers
if i substring out the "d" key and map it as a JSON Array it works, that'll have to be the solution for now...

The field in returned json is an id referenceing to other json, how to parse it

Hi guys I encountered a problem on handling json on Android today. The json I got from the web service looks like the below:
e.g. from https://serviice.somewebite.com/list.json, I got this :
{
"task_id": 5,
"profile_id": 3,
"text": "{profileName} wrote {taskName}",
"created_at": "2015-08-10",
"event": "post"
},
{
"task_id": 6,
"profile_id": 2,
"text": "{profileName} wrote {taskName}",
"created_at": "2015-10-24",
"event": "post"
},
...... (and many similar entities)
the task_id is actually an id linking to other remote json, for the first entity, task_id = 5, which I should get the task json from https://serviice.somewebite.com/task/5.json, like the below:
{
"id": 5,
"name": "Clean house",
"description": "Clean every room in the house",
"state": "assigned",
}
And it is the similar way to get the profile json in the list.json file.
I have been handling json with pojo + retrofit + GSON before, but all the content are in one json, not like this.
What I want is getting all the needed jsons and show them in a listview including created_at(in list.json), task_description(in task.json), task_name(in task.json)
Currently I can only figure out one way to hanlde it. First get the list.json , and then scan the task ids and profile ids in list.json, and then get all the needed json via multiple asynchronous http requests. Seems too much boiler plate code here.
Is there an existing library/framework for this scenario? I am on Android platform using Java. Thanks a lot!

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

Categories