How to get a specific value from json request in Java [duplicate] - java

This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 3 years ago.
When I do this in git bash:
curl -XPOST "https://evepraisal.com/appraisal.json?market=jita&raw_textarea=tritanium&persist=no"
I will get a JSON response like this:
{
"appraisal": {
"created": 1582333288,
"kind":" listing",
"market_name": "jita",
"totals": {
"buy": 13.96,
"sell": 14.62,
"volume": 0.02
},
"items":[
{
"name": "tritanium",
"typeID": 34,
"typeName": "Tritanium",
"typeVolume": 0.01,
"quantity": 2,
"prices": {
"all": {
"avg": 7.792728706899779,
"max": 6660,
"median": 8.49,
"min": 0.01,
"percentile": 10,
"stddev": 11.835529435279334,
"volume": 22008301773,
"order_count": 78
},
"buy": {
"avg": 4.520566796010778,
"max": 6.98,
"median": 5,
"min": 0.01,
"percentile": 6.98,
"stddev": 1.2552914981531016,
"volume": 3832347488,
"order_count": 33
},
"sell": {
"avg": 8.740860647577046,
"max": 6660,
"median": 8.49,
"min": 7.31,
"percentile": 7.31,
"stddev": 12.927105236235532,
"volume": 18175954285,
"order_count": 45
},
"updated": "2020-02-22T00:58:22.615370433Z",
"strategy":" orders"
},
"meta": {
}
}
],
"raw": "tritanium x 2",
"parser_lines": {
"listing": [
0
]
},
"unparsed": {
},
"private": false,
"price_percentage": 100,
"live": false,
"expire_minutes": 21600
}
}
My question is:
How can I pick up a specific attribute from this JSON response?
Like totals:sell:14.62
My second question is:
How can I do that in Java and put the specific attribute in a variable?

Everything depends on what do you exactly need.
If just get one value from response just take it from the response with JSONObject.
you could create Java's POJO for your response, like ResponseWrapper class. Deserialise the response to Java model. Then you can call something like:
double sell = responseObject.getTotals().getSell();
Additional info:
Parse JSON in Java

Related

How to compare json object in a json array by ignoring few attributes in java

I have sample transaction json like below
{
"payload": {
"header": [
{
"messageId": "10a0df00-c55c-4147-a3bf-e10dc9882768",
"transactionId": "10000001",
"customerId": "customer4148",
"customerGroupId": "USA",
"transactionStatus": "completed",
"creationTimestamp": "2022-06-15 06:36:23.798",
"currency": "USD",
"offset": 30
},
{
"messageId": "9cg8f839-ab1e-467f-b679-a3aa4f390f2a",
"transactionId": "10000001",
"customerId": "customer4148",
"customerGroupId": "USA",
"transactionStatus": "completed",
"creationTimestamp": "2022-06-15 06:36:23.798",
"currency": "USD",
"offset": 30
}
]
}
}
I tried using JsonAssert like below but due to vulnerabilities in the jar my CI pipeline is not allowing to use the jar
JSONAssert.assertEquals(expectedResponseBody, responseBody,
new CustomComparator(JSONCompareMode.LENIENT,
new Customization("messageId", (o1, o2) -> true)));
Please help me how can i compare multiple jsonobject under a json array ignoring the messagrId field efficiently

How do I exit a JSON array and enter next object [duplicate]

This question already has answers here:
How do I parse JSON in Android? [duplicate]
(3 answers)
How to parse json parsing Using GSON in android
(5 answers)
How to parse JSON in Java
(36 answers)
Closed 10 months ago.
Below is my JSON format, currently my code is in the currencies, and has obtained the currency code successfully, but now i am stuck in terms on how to exit this array and go to languages object.
My current code basically obtains the name of the country, capital and region from the JSON code stuff attached. I also figured out for it to obtain the currency code, but now I want to get the languages part. This is all done within a while loop in java on AndroidStudio.
[
{
"name":"China",
"topLevelDomain":[
".cn"
],
"alpha2Code":"CN",
"alpha3Code":"CHN",
"callingCodes":[
"86"
],
"capital":"Beijing",
"altSpellings":[
"CN",
"Zhōngguó",
"Zhongguo",
"Zhonghua",
"People's Republic of China",
"中华人民共和国",
"Zhōnghuá Rénmín Gònghéguó"
],
"subregion":"Eastern Asia",
"region":"Asia",
"population":1402112000,
"latlng":[
35.0,
105.0
],
"demonym":"Chinese",
"area":9640011.0,
"gini":38.5,
"timezones":[
"UTC+08:00"
],
"borders":[
"AFG",
"BTN",
"MMR",
"HKG",
"IND",
"KAZ",
"PRK",
"KGZ",
"LAO",
"MAC",
"MNG",
"PAK",
"RUS",
"TJK",
"VNM",
"NPL"
],
"nativeName":"中国",
"numericCode":"156",
"flags":{
"svg":"https://flagcdn.com/cn.svg",
"png":"https://flagcdn.com/w320/cn.png"
},
"currencies":[
{
"code":"CNY",
"name":"Chinese yuan",
"symbol":"¥"
}
],
"languages":[
{
"iso639_1":"zh",
"iso639_2":"zho",
"name":"Chinese",
"nativeName":"中文 (Zhōngwén)"
}
],
"translations":{
"br":"China",
"pt":"China",
"nl":"China",
"hr":"Kina",
"fa":"چین",
"de":"China",
"es":"China",
"fr":"Chine",
"ja":"中国",
"it":"Cina",
"hu":"Kína"
},
"flag":"https://flagcdn.com/cn.svg",
"cioc":"CHN",
"independent":true
},
{
"name":"Macao",
"topLevelDomain":[
".mo"
],
"alpha2Code":"MO",
"alpha3Code":"MAC",
"callingCodes":[
"853"
],
"altSpellings":[
"MO",
"澳门",
"Macao Special Administrative Region of the People's Republic of China",
"中華人民共和國澳門特別行政區",
"Região Administrativa Especial de Macau da República Popular da China"
],
"subregion":"Eastern Asia",
"region":"Asia",
"population":649342,
"latlng":[
22.16666666,
113.55
],
"demonym":"Chinese",
"area":30.0,
"timezones":[
"UTC+08:00"
],
"borders":[
"CHN"
],
"nativeName":"澳門",
"numericCode":"446",
"flags":{
"svg":"https://flagcdn.com/mo.svg",
"png":"https://flagcdn.com/w320/mo.png"
},
"currencies":[
{
"code":"MOP",
"name":"Macanese pataca",
"symbol":"P"
}
],
"languages":[
{
"iso639_1":"zh",
"iso639_2":"zho",
"name":"Chinese",
"nativeName":"中文 (Zhōngwén)"
},
{
"iso639_1":"pt",
"iso639_2":"por",
"name":"Portuguese",
"nativeName":"Português"
}
],
"translations":{
"br":"Macau",
"pt":"Macau",
"nl":"Macao",
"hr":"Makao",
"fa":"مکائو",
"de":"Macao",
"es":"Macao",
"fr":"Macao",
"ja":"マカオ",
"it":"Macao",
"hu":"Makaó"
},
"flag":"https://flagcdn.com/mo.svg",
"independent":false
},
{
"name":"Taiwan",
"topLevelDomain":[
".tw"
],
"alpha2Code":"TW",
"alpha3Code":"TWN",
"callingCodes":[
"886"
],
"capital":"Taipei",
"altSpellings":[
"TW",
"Táiwān",
"Republic of China",
"中華民國",
"Zhōnghuá Mínguó"
],
"subregion":"Eastern Asia",
"region":"Asia",
"population":23503349,
"latlng":[
23.5,
121.0
],
"demonym":"Taiwanese",
"area":36193.0,
"timezones":[
"UTC+08:00"
],
"nativeName":"臺灣",
"numericCode":"158",
"flags":{
"svg":"https://flagcdn.com/tw.svg",
"png":"https://flagcdn.com/w320/tw.png"
},
"currencies":[
{
"code":"TWD",
"name":"New Taiwan dollar",
"symbol":"$"
}
],
"languages":[
{
"iso639_1":"zh",
"iso639_2":"zho",
"name":"Chinese",
"nativeName":"中文 (Zhōngwén)"
}
],
"translations":{
"br":"Taiwan",
"pt":"Taiwan",
"nl":"Taiwan",
"hr":"Tajvan",
"fa":"تایوان",
"de":"Taiwan",
"es":"Taiwán",
"fr":"Taïwan",
"ja":"台湾(中華民国)",
"it":"Taiwan",
"hu":"Tajvan"
},
"flag":"https://flagcdn.com/tw.svg",
"cioc":"TPE",
"independent":true
}
]

Using JSONpath in REST ASSURED java want to extract the data which are in array

The function contains the API in which I can get the value in JSON format. But I want to get the exact ID=2 which is present in JSON How can I get that data using the Java JSON path.
I have to use the maven dependency.
The function contains the API in which I can get the value in JSON format. But I want to get the exact ID=2 which is present in JSON How can I get that data using the Java JSON path.
I have to use the maven dependency.
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.4.0</version>
</dependency>
void get_extract_response_body() {
//Specify Base URL
RestAssured.baseURI="https://reqres.in/api";
//Request object
RequestSpecification httpRequest=RestAssured.given();
//Response Object
Response response=httpRequest.request(Method.GET,"/unknown");
String responseBody= response.getBody().asString();
System.out.println(responseBody);
//Print Response in console window
JsonPath jsonpath= response.jsonPath();
System.out.println(jsonpath.get("data[0]."));
/*
* String id=jsonpath.get("$.data[1].id"); System.out.println(id);
*/
}
{
"page": 1,
"per_page": 6,
"total": 12,
"total_pages": 2,
"data": [
{
"id": 1,
"name": "cerulean",
"year": 2000,
"color": "#98B2D1",
"pantone_value": "15-4020"
},
{
"id": 2,
"name": "fuchsia rose",
"year": 2001,
"color": "#C74375",
"pantone_value": "17-2031"
},
{
"id": 3,
"name": "true red",
"year": 2002,
"color": "#BF1932",
"pantone_value": "19-1664"
},
{
"id": 4,
"name": "aqua sky",
"year": 2003,
"color": "#7BC4C4",
"pantone_value": "14-4811"
},
{
"id": 5,
"name": "tigerlily",
"year": 2004,
"color": "#E2583E",
"pantone_value": "17-1456"
},
{
"id": 6,
"name": "blue turquoise",
"year": 2005,
"color": "#53B0AE",
"pantone_value": "15-5217"
}
],
"support": {
"url": "https://reqres.in/#support-heading",
"text": "To keep ReqRes free, contributions towards server costs are appreciated!"
}
}
This Response helped me to find the key-value from each data.
There are 2 JsonPath:
JsonPath Rest-Assured:
JsonPath jsonpath= response.jsonPath();
int id = jsonPath.getInt("data[1].id");
System.out.println(id); //2
JsonPath Jayway:
int id = com.jayway.jsonpath.JsonPath.read(response.asString(), "$.data[1].id");
System.out.println(id); //2

Complex schema validation in Karate

I'm trying to validate the response schema with karate but facing issue with array.
Attaching the response and feature as well as my schema.json.
Response -
{
"page": 1,
"per_page": 6,
"total": 12,
"total_pages": 2,
"data": [
{
"id": 3,
"email": "emma.wong#reqres.in",
"first_name": "Emma",
"last_name": "Wong",
"avatar": "https://reqres.in/img/faces/3-image.jpg"
},
{
"id": 4,
"email": "eve.holt#reqres.in",
"first_name": "Eve",
"last_name": "Holt",
"avatar": "https://reqres.in/img/faces/4-image.jpg"
},
{
"id": 5,
"email": "charles.morris#reqres.in",
"first_name": "Charles",
"last_name": "Morris",
"avatar": "https://reqres.in/img/faces/5-image.jpg"
},
{
"id": 6,
"email": "tracey.ramos#reqres.in",
"first_name": "Tracey",
"last_name": "Ramos",
"avatar": "https://reqres.in/img/faces/6-image.jpg"
}
],
"support": {
"url": "https://reqres.in/#support-heading",
"text": "To keep ReqRes free, contributions towards server costs are appreciated!"
}
}
Scenario: Get all Users and validate schema
Given url getUrl
When method Get
Then status 200
And print response
Then match response == '#object'
* string jsonSchemaExpected = read('file:src/test/resources/features/sample/responseSchema.json')
And print response.data.length
And match response == jsonSchemaExpected
responseSchema.json
{
"page": "#number",
"per_page": "#number",
"total": "#number",
"total_pages": "#number",
"data": "#[] #object",
"support": "#object"
}
The only observation I have is if you cast to a string, you won't be able to do any matching.
Instead of * string jsonSchemaExpected do * def jsonSchemaExpected.

How to index and search nested documents/structured data in Lucene or similar libraries?

I have a structured JSON data in the following form:
{
"id": 42,
"name": "hand",
"quantity": 2,
"digits": [
{
"id": 43,
"name": "thumb",
"quantity": 1,
"components": [
{
"id": 44,
"name": "thumb",
"position": 0
}
]
},
{
"id": 45,
"name": "fingers",
"quantity": 4,
"components": [
{
"id": 46,
"name": "index",
"position": 1
},
{
"id": 47,
"name": "middle",
"position": 2
},
{
"id": 48,
"name": "ring",
"position": 3
},
{
"id": 49,
"name": "little",
"position": 4
}
]
}
]
}
I need to index these data, using Java, so that it would be possible afterwards to make queries to get the needed information.
To that end a solution could be using Apache Lucene which supports nested documents since version 3.4. However, I could not find any tutorial nor a simple example on how a nested document can be created.
Can anyone explain how to create a Lucene document for structured data?
Alternatively, are there other libraries similar to Lucene which better support indexing and searching of structured data?
A simple solution in your case is to use path enumerations ("Dewey Decimal"). For example, yor first three tems would be "42", "42.43", and "42.43.44", while your fourth item would be "42.45". Make sure your slots are large enough for the largest number of items you will need -- for example, "042.043.044".

Categories