Trying to get specific data from a query response - java

I'm running a JUnit test, and I'm having some issues with a function where I have to get specific data from a query response. Here's a function I'm testing, note .get("data") at the end:
protected JsonNode getFunctionIds(FilterInputModel paramA) {
String paramB = "here's a query";
String idsQuery = setFunctionFieldsForQuery(paramA, paramB);
...
return Objects.requireNonNull(webClient.post()
.uri("/query")
.header(HttpHeaders.AUTHORIZATION, getSessionId())
.body(BodyInserters.fromMultipartData(queryMap))
.retrieve()
.bodyToMono(JsonNode.class)
.block())
.get("data");
}
Note that the inputModel is a class containing strings and string lists.
Here's a test I wrote. I'm getting an AssertionFailedError with it, and I vaguely know why, but I don't know how to get the right data.
#Test
void getFunctionIds() throws IOException {
Path filePath = Path.of("documents/__files/getFunctionIds.json");
String body = Files.read(filePath.toFile(), Charset.defaultCharset());
wireMockServer.stubFor(post(urlEqualTo("/api/query"))
.willReturn(aResponse()
.withStatus(200)
.withHeader("Content-Type", "application/json")
.withBody(body))
);
JsonNode jsonNode = new ObjectMapper().readValue(body, JsonNode.class);
String bodyData = new ObjectMapper().writeValueAsString(jsonNode);
JsonNode vaultData = serviceTest.getFunctionIds(inputModel);
String response = new ObjectMapper().writeValueAsString(vaultData);
assertEquals(bodyData, response);
}
Next is a query response (paramB) I got when sending it to the vault. It is stored as a String bodyData.
{
"someOtherData": ...
{
...
},
"data": [
{
"id": "V4600000002G003"
},
{
"id": "V4600000002H214"
},
{
"id": "V4600000002I001"
},
{
"id": "V4600000002J001"
},
{
"id": "V4600000002J062"
},
{
"id": "V4600000002K047"
},
{
"id": "V4600000002K071"
},
{
"id": "V4600000002K171"
}
]
}
And as I said, all I got is an AssertionFailedError, because I'm asserting the whole query response (bodyData) with just the "data" part of the JSON, which is stored in String response.
Here's the error:
Expected :{
"someOtherData"... + "data", actually the whole query response (paramB) i mentioned already.
Actual:
[
{
"id": "V4600000002G003"
},
{
"id": "V4600000002H214"
},
{
"id": "V4600000002I001"
},
{
"id": "V4600000002J001"
},
{
"id": "V4600000002J062"
},
{
"id": "V4600000002K047"
},
{
"id": "V4600000002K071"
},
{
"id": "V4600000002K171"
}
]
Is there a way to catch just the Actual part of the query response, to avoid the AssertionFailedError? That would solve my problem, obviously.

Related

How to implement Post API JSON with Spring?

I'm having difficulty implementing a JSON to send as a POST call in Spring.
Which is the fastest and most effective way to turn this json into a java object or a map and make the call?
below is an example of a json to send:
{
"apiVersion": "apps/v1",
"kind": "Deployment",
"metadata": {
"name": "edge-ws"
},
"spec": {
"selector": {
"matchLabels": {
"run": "edge-ws"
}
},
"replicas": 1,
"template": {
"metadata": {
"labels": {
"run": "edge-ws"
}
},
"spec": {
"containers": [
{
"name": "edge-ws",
"image": "server-tim:latest",
"imagePullPolicy": "Never",
"ports": [
{
"containerPort": 80
}
]
}
]
}
}
}
}
this and the second body that has a value (nodeport) that must be taken from a field entered by the user front end side.(page created in html)
{
"apiVersion": "v1",
"kind": "Service",
"metadata": {
"name": "edge-ws",
"labels": {
"run": "edge-ws"
}
},
"spec": {
"type": "NodePort",
"ports": [
{
"port": 8080,
"targetPort": 80,
"nodePort": 30200,
"protocol": "TCP",
"name": "http"
}
],
"selector": {
"run": "edge-ws"
}
}
}
Both files must be sent with a single click on a button on the front end side.the first call with the first body starts and if everything is ok the second body starts
What should the class that maps objects look like? What should the controller look like instead?
They also gave me an address to call that can only be used on the machine, how can I test this call locally?
Thanks in advance!
You can use google's Gson library to convert the JsonString to Object and then use below code:
Gson gson = new Gson();
Object requestObject = gson.fromJson(jsonString, Object.class);
ResponseObject responseObject = restTemplate.postForObject(url, requestObject, ResponseObject.class);

how to access jsonarray using retrofit

how to access districtID(key) value and name(key) value using retrofit ?
this is json file...
{
"error": false,
"message": "District successfully fetched.",
"districts": [
{
"districtID": "DIS260920181",
"name": "Raipur"
},
{
"districtID": "DIS260920182",
"name": "Bilaspur"
},
{
"districtID": "DIS011020186",
"name": "korba"
},
{
"districtID": "DIS011020187",
"name": "jagdalpur"
},
{
"districtID": "DIS021020188",
"name": "surguja"
},
{
"districtID": "DIS021020189",
"name": "Mungeli"
}
]
}
Please help :(
Convert JSON Array into POJO classes and then call api using retrofit network call.
Use this link
copy your json and it gives you two model class you should put the parent class which contains error , message and districts as your output in your request. something like this
#GET("your_url")
Call<ModelExample> nameOfMethod();
And then you have list of districts. you can access to the items and districtID and name
I hope it helps you :)
for onResponse:
--------------------------
Call<ModalClass> daoCall = api.getconnectdata();
modelclass.enqueue(new Callback<ModalClass>() {
#Override
public void onResponse(Call<ModalClass> call, Response<ModalClass>
response) {
if(response.isSuccessful()){
modelclass= response.body();
List<Districts> list = modelclass.getAddData().getData();
adapter = new CustomListAdapter(getApplicationContext(),list);
listView.setAdapter(adapter);
}
}

How to retrieve value in the response of restassured

I got a response as below by using rest-assured:
{
"data": {
"hasMore": true,
"galleries": [
{
"pic": "/xianfu/34b9a6d07bc91a659156d79da1d82f7d18432.jpg",
"picInZoom": "/xianfu/34b9a6d07bc91a659156d79da1d82f7d18432.jpg#200w"
},
{
"pic": "/xianfu/ca0b796b7e0f67cc9f78c73334a6404d26624.jpg",
"picInZoom": "/xianfu/ca0b796b7e0f67cc9f78c73334a6404d26624.jpg#200w"
},
{
"pic": "/xianfu/30da40b9c1eff6154989fc3c78c8292d43008.jpg",
"picInZoom": "/xianfu/30da40b9c1eff6154989fc3c78c8292d43008.jpg#200w"
},
{
"pic": "/xianfu/b59bda5cf828692c4af3a654f9b7309743008.jpg",
"picInZoom": "/xianfu/b59bda5cf828692c4af3a654f9b7309743008.jpg#200w"
},
{
"pic": "/xianfu/ac72069a937f03012532c32ae469a87e28672.jpg",
"picInZoom": "/xianfu/ac72069a937f03012532c32ae469a87e28672.jpg#200w"
},
{
"pic": "http://p0.baidu.com/xianfu/dcce14b596ad9d350cc2b64e039bf0a434816.jpg",
"picInZoom": "http://p0.baidu.com/xianfu/dcce14b596ad9d350cc2b64e039bf0a434816.jpg#200w"
},
{
"pic": "/xianfu/22fa3ac23efb0724202ac8fcaac01b5f16384.jpg",
"picInZoom": "/xianfu/22fa3ac23efb0724202ac8fcaac01b5f16384.jpg#200w"
},
{
"pic": "/xianfu/7b40420eef11b59af3aa0d1c0230cedc24576.jpg",
"picInZoom": "/xianfu/7b40420eef11b59af3aa0d1c0230cedc24576.jpg#200w"
}
]
},
"code": 0,
"msg": "Success"
}
How can I get the value of first pic in response, with JAVA code, thanks a lot!
Try to convert the response into a string, with the toString() method
then transform that string into an object, like this:
JSONObject jsonObj = new JSONObject(homeAddress);
and from there, you can access it like this:
String pic = jsonObj.getJSONObject("data").getJSONArray("galleries").getJSONObject(0).getString("pic");

How to get json value using GSON from json tree

I have a json such as below
{
"apiVersion": "v1",
"metadata": {
"status": {
"statusCode": 0
},
},
"stuff": [
{
"name": {
"text": "red"
},
"properties": [
{
"attributes": {
"shade": "dark"
},
"component": {
"id": "BA1",
}
"type": "Color"
}
]
},
{
"name": {
"text": "Toyota Camry"
},
"properties": [
{
"attributes": {},
"component": {
"id": "MS",
},
"type": "Vehicle"
}
]
},
]
}
I'm using GSON to parse the results like this:
Gson gson = new Gson();
JsonObject json = (JsonObject) gson.fromJson(in, JsonObject.class);
System.out.println(json.get("apiVersion").getAsString());
I can get the apiVersion but don't know how to get elements that are inside the json tree. For example, type...what if I want to output all the different type..in this case Color and Vehicle
I must be missing something here, but why can't you nest calls to getJsonObject? For example, to get the status code:
System.out.println(json.getAsJsonObject("metadata")
.getAsJsonObject("status")
.get("statusCode").getAsInt());
You can create an object in that matter and to parse the json to it (with GSON):
ParsedObject parsedObject = new Gson().fromJson(json, ParsedObject.class);
public class ParsedObject {
#SerializedName(value = "apiVersion")
private String mApiVersion;
#SerializedName(value = "metadata")
private Metadata mMetadata;
}

Parsing JSON with Jackson return null

I'm training my self on java using API. The subject of my exercise is to ask google books API in order to take some infos about books. I use Jersey as a client and Jackson to parse the JSON.
My problem is that when i run the JerseyVolumeGet() , the response is this one :
Volume{title='null', numberOfPages=null, author='null'}
Why ? Where is my mistake ? I suspect i get wrong when parsing the JSON but don't see where exactly..
Here my getClass ( the search url is barcoded , it's not a problem for me)
public class JerseyVolumeGet {
public static void main(String[] args) {
try {
Client client = Client.create();
WebResource webResource = client
.resource("https://www.googleapis.com/books/v1/volumes?q=1984");
ClientResponse response = webResource.accept("application/json")
.get(ClientResponse.class);
if (response.getStatus() != 200) {
throw new RuntimeException("Noob you Failed : HTTP error code : "
+ response.getStatus());
}
String output = response.getEntity(String.class);
// read from file, convert it to user class
ObjectMapper mapper = new ObjectMapper();
Volume volume = mapper.readValue(output, Volume.class);
// display to console
System.out.println(volume);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Here the JSON result of my query :
{
"kind": "books#volumes",
"totalItems": 641,
"items": [
{
"kind": "books#volume",
"id": "RY8yQWeDVFYC",
"etag": "Lf0P50PVz9c",
"selfLink": "https://www.googleapis.com/books/v1/volumes/RY8yQWeDVFYC",
"volumeInfo": {
"title": "(1984).",
"subtitle": "",
"authors": [
"Guy Serbat",
"Jean Taillardat",
"Gilbert Lazard"
],
"publisher": "Peeters Publishers",
"publishedDate": "1984-01-01",
"description": "(Peeters 1984)",
"industryIdentifiers": [
{
"type": "ISBN_10",
"identifier": "2904685030"
},
{
"type": "ISBN_13",
"identifier": "9782904685033"
}
],
"readingModes": {
"text": false,
"image": true
},
"pageCount": 280,
"printType": "BOOK",
"categories": [
"Language Arts & Disciplines"
],
"contentVersion": "1.1.1.0.preview.1",
"imageLinks": {
"smallThumbnail": "http://bks9.books.google.fr/books?id=RY8yQWeDVFYC&printsec=frontcover&img=1&zoom=5&edge=curl&source=gbs_api",
"thumbnail": "http://bks9.books.google.fr/books?id=RY8yQWeDVFYC&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api"
},
"language": "fr",
"previewLink": "http://books.google.fr/books?id=RY8yQWeDVFYC&printsec=frontcover&dq=1984&hl=&cd=1&source=gbs_api",
"infoLink": "http://books.google.fr/books?id=RY8yQWeDVFYC&dq=1984&hl=&source=gbs_api",
"canonicalVolumeLink": "http://books.google.fr/books/about/1984.html?hl=&id=RY8yQWeDVFYC"
},
"saleInfo": {
"country": "FR",
"saleability": "NOT_FOR_SALE",
"isEbook": false
},
"accessInfo": {
"country": "FR",
"viewability": "PARTIAL",
"embeddable": true,
"publicDomain": false,
"textToSpeechPermission": "ALLOWED",
"epub": {
"isAvailable": false
},
"pdf": {
"isAvailable": false
},
"webReaderLink": "http://books.google.fr/books/reader?id=RY8yQWeDVFYC&hl=&printsec=frontcover&output=reader&source=gbs_api",
"accessViewStatus": "SAMPLE",
"quoteSharingAllowed": false
},
"searchInfo": {
"textSnippet": "(Peeters 1984)"
}
},
more items...
}
Then , i've a Volume.class like that :
#JsonIgnoreProperties(ignoreUnknown=true)
public class Volume {
#JsonProperty("title")
String title;
#JsonProperty("pageCount")
Integer pageCount;
#JsonProperty("authors")
String authors;
getters , setters and toString..
You need to model the full JSON structure, something like this:
public class BookData {
String kind;
Integer totalItems;
List<Item> items;
}
public class Item {
String kind;
String id;
//...
Volume volumeInfo;
}
Then you can use ObjectMapper to read the BookData:
BookData bookData = new ObjectMapper().readValue(output, BookData.class);
And pull out the Volume info from each Item in the BookData.

Categories

Resources