JSON Response Value says Null Rest Assured - java

My JSON Response reads something like:
{
"_embedded":{
"contents": [
{
"data": 1234,
"success": true,
}
]
}
}
I am attempting to extract the the success message and data. However my console output keeps reading null.
Once extracting the Response here is my code that receives a Null response using Rest Assured:
String res = response.asString():
JsonPath js = new JsonPath(res);
String success = js.get("_embedded[0].contents[0].success");
String data = js.get("_embedded[0].contents[0].data");
System.out.println(success);
System.out.println(data);
My response for both success and data is null

From your JSON sample, it looks like _embedded is not a list. _embedded[0] might return null because there is no list named _embedded when you try to extract the success value using "_embedded[0].contents[0].success".
Extract the success value by using
js.get("$._embedded.contents[0].success");

Related

When using Rest Assured, if I send a post request to summit data to server, how can I write "ABC":["XYZ"] this value in LinkedHashmap

Request body is:-
{
"request":
{
"body":
{
"ABC":["XYZ"],
"PASSWORD": "password"
}
}
MY CODE:-
I am getting error in response because the ABC value is going in string format
Map body = new LinkedHashMap(6);
body.put("ABC","XYZ");
body.put("PASSWORD","password");
what is the correct way to write this request body using LinkedHashMap in restAssured
"ABC":["XYZ"],
You just need change it to List<String>
body.put("ABC", Arrays.asList("XYZ"));

Issue in passing string in Request Body

I am facing an issue while making a request body to do an API call in Java.
Required Body
{
"id" : [1,2]
}
I have an integer array with me lets say arr, I am creating the request something like:-
JSONObject jsonObject = new JSONObject();
jsonObject.put("id",Arrays.toString(arr));
String stringBody = jsonObject.toJSONString();
RequestSpecification specification = RestAssured.with();
specification.body(stringBody);
Response response = specification.post(endpoint);
What it actually does is make the request body as something like below.
{
"id" : "[1,2]"
}
As it sends the value as String so my server throws an error, Expected a list of items but got type \"unicode\".
Can somebody help me in here. How do I send it in raw format instead of String.
Use
jsonObject.put("id",Arrays.asList(arr));
to build the json body.

Retrofit - Receive JSON Array Always Return NULL

I have code :
InterfaceAPI:
#GET("/api/getUserAsset?")
Call<MyObject> getUserAsset(#Query("user_id") String userId);
The Library said : HTTP OK 200
MyObject.java :
#SerializedName("name")
private String name;
JSON Response from API :
[{"name":"bob"}]
When i call the method getUserAsset i always get NULL, why?
Your JSON response is an array.
it should be : {"name" : "bob"} if you want to be able to deserialize it correctly.

How to I decode the headers of a message using Gmail-API using Java?

I am working on a fragment in android studio whose purpose is to display To/From, Subject, and the body of the message. So far, I am able to retrieve, decode, and display the body. I tried using a similar method for the headers but for some reason it isn't decoding properly, or my method calls aren't getting the correct information. Here is the code I am working with:
String user = "me";
String query = "in:inbox is:unread";
textView.setText("Inbox");
ListMessagesResponse messageResponse =
mService.users().messages().list(user).setQ(query).setMaxResults(Long.valueOf(1)).execute();
List<Message> messages = messageResponse.getMessages();
for(Message message : messages){
Message message2 = mService.users().messages().get(user, message.getId()).execute();
//Get Headers
byte[] headerBytes = Base64.decodeBase64(message2.getPayload().getParts().get(0).getHeaders().get(0).getName().toString().trim()); // get headers
String header = new String(headerBytes, "UTF-8");
//Get Body
byte[] bodyBytes = Base64.decodeBase64(message2.getPayload().getParts().get(0).getBody().getData().trim().toString()); // get body
String body = new String(bodyBytes, "UTF-8");
messageList.add(header);
messageList.add(body);
}
return messageList;
The section under // get body works. But the section under //Get Headers returns data with weird symbols which include black diamonds with white question marks inside and letters in random order. I have tried many different combinations and orders for the method calls in the Base64.decodeBase64 statement for headerBytes but wasn't able to succeed. Is there something I am missing?
Edit: I looked at the gmail-api documentation on the google developers site and I still am confused on how the header information is stored and how to retrieve specific things such as To, From, and Subject. That might be my problem since I may not be targeting the correct data.
If I list messages and get the first one, we can see what the message looks like:
Request
format = metadata
metadataHeaders = From,To,Subject
fields = payload/headers
GET https://www.googleapis.com/gmail/v1/users/me/messages/15339f3d12042fec?format=metadata&metadataHeaders=To&metadataHeaders=From&metadataHeaders=Subject&fields=payload%2Fheaders&access_token={ACCESS_TOKEN}
Response
{
"payload": {
"headers": [
{
"name": "To",
"value": "Emil <emtholin#gmail.com>"
},
{
"name": "From",
"value": "\"BernieSanders.com\" <info#berniesanders.com>"
},
{
"name": "Subject",
"value": "5,000,000"
}
]
}
}
As you can see, the values you are looking for are in the headers. You just have to sort them out in Java and you are done. The headers are not encoded like the body, so there is no need to do any decoding.

Plain string template query for elasticsearch through java API?

I have a template foo.mustache saved in {{ES_HOME}}/config/scripts.
POST to http://localhost:9200/forward/_search/template with the following message body returns a valid response:
{
"template": {
"file": "foo"
},
"params": {
"q": "a",
"hasfilters": false
}
}
I want to translate this to using the java API now that I've validated all the different components work. The documentation here describes how to do it in java:
SearchResponse sr = client.prepareSearch("forward")
.setTemplateName("foo")
.setTemplateType(ScriptService.ScriptType.FILE)
.setTemplateParams(template_params)
.get();
However, I would instead like to just send a plain string query (i.e. the contents of the message body from above) rather than build up the response using the java. Is there a way to do this? I know with normal queries, I can construct it like so:
SearchRequestBuilder response = client.prepareSearch("forward")
.setQuery("""JSON_QUERY_HERE""")
I believe the setQuery() method wraps the contents into a query object, which is not what I want for my template query. If this is not possible, I will just have to go with the documented way and convert my json params to Map<String, Object>
I ended up just translating my template_params to a Map<String, Object> as the documentation requires. I utilized groovy's JsonSlurper to convert the text to an object with a pretty simple method.
import groovy.json.JsonSlurper
public static Map<String,Object> convertJsonToTemplateParam(String s) {
Object result = new JsonSlurper().parseText(s);
//Manipulate your result if you need to do any additional work here.
//I.e. Programmatically determine value of hasfilters if filters != null
return (Map<String,Object>) result;
}
And you could pass in the following as a string to this method:
{
"q": "a",
"hasfilters": true
"filters":[
{
"filter_name" : "foo.untouched",
"filters" : [ "FOO", "BAR"]
},
{
"filter_name" : "hello.untouched",
"list" : [ "WORLD"]
}
]
}

Categories

Resources