Get data from outside the root level of response - java

I'm still kind of new to REST and haven't been able to figure this one out.
I have a response like this one:
{
"StatusCode": 200,
"Result": {
"CustomerStuff": {
"Name": "John",
"State": "Oregon",
"GetEmail": false
},
"eText": "Will only get paper mail. "
}
}
I would normally save the response body as a string and then use a JsonPath to get what I need.
String responseBody = given().body().when().etc...;
JsonPath jsonPath = new JsonPath(responseBody).setRoot("Result.CustomerStuff");
Then get what I need:
String name = jsonPath.get("name");
I can't figure out how to get the, "eText" value. It's not in the same segment of the response.
Any suggestions?

You should use
JsonPath jsonPath = new JsonPath(responseBody).setRoot("Result")
And then call jsonPath.get("eText") in order to get the value you want.
You can still access CustomerStuff with jsonPath.get("CustomerStuff")

Related

How To Extract Json Data Filed With RestApi?

i make a post to an api with rest assured. and than i try to make sure expected data from responsed data ,
but i got some errors like this -> "java.lang.IllegalArgumentException: The parameter "data" was used but not defined. Define parameters using the JsonPath.params(...) function"
my code:
String payload_data = "{" +
"\"Time\":1638057600, " +
"\"exampleType\":example, " +
"\"Id\":[2]}";
RestAssured.defaultParser = Parser.JSON;
given().
contentType(ContentType.JSON).
body(payload_data).
when().
post(api_url).
then().
statusCode(200).
body("data.examples.2.exampleData", equalTo("33"));
}
my json data
{
"success": true,
"data": {
"examples": {
"2": {
"ex_data": 0,
"exampleData": 33,
"data_ex": 0,
}
}
}
First, I tested path "data.examples.2.exampleData" with your json, it works fine. No problem.
You made some mistakes here.
Your payload is invalid json.
{
"Time": 1638057600,
"exampleType": example, //it must be number or String with double quote
"Id": [
2
]
}
You are comparing 2 things with different data types.
"data.examples.2.exampleData" --> int 33
equalTo("33") --> String "33"
Fix: body("data.examples.2.exampleData", equalTo(33));

not able to create Java Object from Json having double quote in value

I have same query. My JSON is as below.
String json="{ "credentials": { "password": "Password"123", "emailAddress": "skylineadmin#gmail.com" }, "clientTimeMs": 1582006455421, "callerRole": 0 }"
key = password and value is "Password"123" it contains " (double quote).. I am not able to create a java object from this json as it is invalidated.
Gson gson = new Gson();
gson.fromJson(json, PasswordResetDetails.java);
Above code snippet is not Working.
If you are doing this for learning / testing purpose all you need to do is escaping the double quote using :
String json="{ "credentials": { "password": "Password\"123", "emailAddress": "skylineadmin#gmail.com" }, "clientTimeMs": 1582006455421, "callerRole": 0 }"
If this is a real scenario then I would like to suggest to change the source in order to make sure it provides valid JSON.
There are countless possibilities to check if your JSON is valid (JSON linting), here's one.

RestAssured: posting json request having both String and Integer

I just want to POST json request(using restassured), for such json:
{
"userId": 1,
"id": 111,
"title":"test msg"
"body": "this is test msg"
}
Im defining base uri, and trying to use hashmap:
RestAssured.baseURI = "http://localhost:8888";
RestAssured.basePath = "/posts/";
Map<String, String> map = new HashMap<String, String>();
map.put("userId", 1);
map.put("id", 111);
map.put("title","test Post");
map.put("body","this is test body");
And of course its "red", because of trying put integer as string.
I'm changing to String.valueOf() for my 1 and 111 numbers,
then successfully posting request with smth like
given()
.contentType("application/json")
.body(map)
.when()
.post("/")
.then()
.statusCode(201);
But response is incorrect(comparing with needed json):
{
"id": "111",
"title": "test Post",
"body": "this is test body",
"userId": "1"
}
2 points here:
- id and userId posted as Strings
- order is incorrect
So, question:
what is the best approach in such situations, to correctly post needed request, in correct order and with int values for id and usedId?
Thanks!
What you can do is use Map<String, Object> instead of Map<String,String>.
Also, the order is not preserved for the JSON Object. You cannot and should not rely on the ordering of elements within a JSON object.
An object is an unordered set of name/value pairs.
You can check out JSON specification for more info.

codenameone display entire json response message not just a single node

I am calling a parcel tracking json service using codenameone java code.
Here is the full json response:
{
"success": true,
"results": {
"tracking_reference": "DY954563460NZ",
"message_id": "682c9b69-7f90-48c6-a36d-3b371e203a96",
"message_datetime": "2016-11-11T08:08:05.0000000Z",
"service": "",
"carrier": ""
}
}
I would like to create a popup that displays the entire response - but all the examples I can see only show how to get the results node.
Here is what I am currently showing:
"results": {
"tracking_reference": "DY954563460NZ",
"message_id": "682c9b69-7f90-48c6-a36d-3b371e203a96",
"message_datetime": "2016-11-11T08:08:05.0000000Z",
"service": "",
"carrier": ""
}
This is because I am using this code to get this specific branch:
Object responseMessage = null;
responseMessage = apiResponse.get("results");
Dialog d = new Dialog("Response");
d.setScrollable(true);
d.show("Response Message", responseMessage.toString(), "OK", null);
According to this website there is a special node called 'root' which should do the trick but it errors out.
https://www.codenameone.com/javadoc/com/codename1/io/JSONParser.html
Any idea how I can display the entire response message?
Thanks
Remove this line:
responseMessage = apiResponse.get("results");

How to read JSON object from URL query string

I have a URL request like this:
http://localhost:8080:_dc=1367504213107&filter[0][field]=site&filter[0][data][type]=string&filter[0][data][value]=test&filter[1][field]=address&filter[1][data][type]=string&filter[1][data][value]=Columbus
This is the URL request that I get from browser.
From this URL, I need to get the filter related data as a JSON object.
Basically I have filter parameters like these in the requested URL:
filter[0][field]=site
filter[0][data][type]=string
filter[0][data][value]=test
filter[1][field]=address
filter[1][data][type]=string
filter[1][data][value]=Columbus
I am using the Spring MVC framework.
Those URL parameters aren't in JSON format. I'm not sure what your question / problem is here... can't you just read in each of those parameters from the URL and then parse the data out of the strings as you need? You could take it as a single parameter and tokenize based on a custom character, or you could just loop through all the parameters and parse each one and add them to an array.
Are you saying that you need to return the data in JSON format? Get your data using the parsed parameters as I described above, then when you have the data merely serialize that object and pass it back over the wire as the body of the response. You'll want to use a JSON serialization library like Jackson which will write the object to a string in JSON for you.
This is what that data would probably look like if it were written in JSON:
{
"filter":
[
{
"field": "site",
"data":
{
"type": "string",
"value": "test"
}
},
{
"field": "address",
"data":
{
"type": "string",
"value": "Columbus"
}
}
]
}
Java code that translates from the above JSON to your-format:
JSONObject root = new JSONObject(json);
JSONArray filters = root.getJSONArray("filter");
for (int i = 0; i < filters.length(); i++)
{
JSONObject filter = filters.getJSONObject(i);
String field = filter.getString("field");
JSONObject data = filter.getJSONObject("data");
String dataType = data.getString("type");
String dataValue = data.getString("value");
System.out.println("filter[" + i + "][field]=" + field);
System.out.println("filter[" + i + "][data][type]=" + dataType);
System.out.println("filter[" + i + "][data][value]=" + dataValue);
}
Your data format does not appear to be standard, so you will have to parse it yourself.

Categories

Resources