Find value in JSON HTTP response - java

I want to get the value of city from the below httpResponse (JSON Response) where fruit is Apple. I am unable to find a way to add this condition to my groovy script.
{
"userInformation": {
"Name": "John",
"Location": "India"
},
"details": [
{
"fruit": "Apple",
"color": "Red",
"city": "New Delhi",
"luckyNumber": 10
},
{
"fruit": "Banana",
"color": "yellow",
"city": "Goa",
"luckyNumber": 12
}
]
}

JsonSlurper is what you need. It parses JSON object to a plain Map which can be then easily navigated to find the desired value.
import groovy.json.JsonSlurper
def input = '''{
"userInformation": {
"Name": "John",
"Location": "India"
},
"details": [
{
"fruit": "Apple",
"color": "Red",
"city": "New Delhi",
"luckyNumber": 10
},
{
"fruit": "Banana",
"color": "yellow",
"city": "Goa",
"luckyNumber": 12
}
]
}
'''
def slurped = new JsonSlurper().parseText(input)
slurped.details.find { it.fruit == 'Apple' }?.city

Related

How to get json key values by another key value

I have a JSON output like this:
{
"items": [
{
"id": "1",
"name": "Anna",
"values": [
{
"code": "Latin",
"grade": 1
},
{
"code": "Maths",
"grade": 5
}
]
},
{
"id": "2",
"name": "Mark",
"values": [
{
"code": "Latin",
"grade": 5
},
{
"code": "Maths",
"grade": 5
}
]
}
]
}
I need to get field values for "name": "Anna". I am getting RestAssured Response and would like to use my beans to do that, but I can also use jsonPath() or jsonObject(), but I don't know how. I searched many topics but did not find anything.

ArrayList put a field in each map of the list according to the value of another arrayList

I have an arraylist:
{
"response": [
{
"number": "229425941 ",
"CURRENCY": "EUR",
"account": "0026.5501.90.0490520505",
"branch": "0154",
"product": "geia",
"service": "0026.0002.62.0300162968",
"amount": 20000,
"expDate": "2019-09-20",
"bank": "0026",
"name": "A name "
},
{
"number": "229425941 ",
"CURRENCY": "EUR",
"account": "0026.5501.90.0490520505",
"branch": "0154",
"product": "geia",
"service": "0026.0002.62.0300162968",
"amount": 20000,
"expDate": "2019-09-20",
"bank": "0027",
"name": "A name "
},
]
}
and I have a second arraylist which contains details for each bank. The list is this:
"details": [
{
"bankCode": "010",
"bankDescription": "BANK",
},
{
"bankCode": "011",
"bankDescription": "NATIONAL",
},
{
"bankCode": "012",
"bankDescription": "ALPHA",
}
]
}
Now I want to loop through the first list and put the bankDescription field in each object of the list according to the bankCode and the bankDescription of the second list. I made a stream for the first arrayList:
firtsList.stream().forEach(a -> {
a.put();
});
My guess is that somehow to loop through the second list but I don't know an efficient way. My output must be something like this:
{
"response": [
{
"number": "229425941 ",
"CURRENCY": "EUR",
"account": "0026.5501.90.0490520505",
"branch": "0154",
"product": "geia",
"service": "0026.0002.62.0300162968",
"amount": 20000,
"expDate": "2019-09-20",
"bank": "010",
"bankDesc: "BANK"
"name": "A name "
},
{
"number": "229425941 ",
"CURRENCY": "EUR",
"account": "0026.5501.90.0490520505",
"branch": "0154",
"product": "geia",
"service": "0026.0002.62.0300162968",
"amount": 20000,
"expDate": "2019-09-20",
"bank": "011",
"bankDesc: "NATIONAL"
"name": "A name "
},
]
}
secondList.stream().filter(bic -> firstList.stream()
.anyMatch(c -> StringUtils.substring((String) c.get("bankDesc"), 1, 3)
.equals(bic.get("bankCode"))));
Have a model/dto to simplify the process. You can use objectMapper to map Json directly into POJO.
Assuming you disregard all advice and proceed with Json/Map, here's how you can proceed:
//Build a dictionary from the data
Map<String, String> bankCodeToDescriptionMap = secondList.stream().collect(Collectors.toMap(v -> v.get("bankCode"), v -> v.get("bankDescription")));
firstList.stream().forEach(a -> {
a.put("bankDescription", bankCodeToDescriptionMap.get(v.get("bankCode")));
});
Do not iterate over the list for each value. It will be too slow

How to loop over an ArrayList which contains a map?

Currently I'm using rest-assured to hit an endpoint and in turn store any JSON data matches via an ArrayList and HashMap.
I can see that I'm receiving a response back, but how do I loop over an ArrayList when it contains an internal HashMap?
As you can see from the JSON data below, I'm expecting to output all values / matches stored within the ArrayList.
My Code:
public void apiTest() {
String position = "Attacker";
String role = "PLAYER";
Response response = given()
.spec(footballCompetitions_requestSpecification)
.when().get(EndPoint.TEAMS + EndPoint.SQUAD);
ArrayList<Map<String, ?>> allPlayers = response.path
("squad.findAll { it.role == '%s' }.findAll { it.position == '%s' }", position, role);
Example JSON Data:
{
"id": 66,
"area": {
"id": 2072,
"name": "England"
},
"activeCompetitions": [
{
"id": 2021,
"area": {
"id": 2072,
"name": "England"
},
"name": "Premier League",
"code": "PL",
"plan": "TIER_ONE",
"lastUpdated": "2019-01-03T23:39:45Z"
},
{
"id": 2001,
"area": {
"id": 2077,
"name": "Europe"
},
"name": "UEFA Champions League",
"code": "CL",
"plan": "TIER_ONE",
"lastUpdated": "2018-12-13T18:55:02Z"
}
],
"name": "Manchester United FC",
"shortName": "Man United",
"tla": "MNU",
"crestUrl": "http://upload.wikimedia.org/wikipedia/de/d/da/Manchester_United_FC.svg",
"address": "Sir Matt Busby Way Manchester M16 0RA",
"phone": "+44 (0161) 8688000",
"website": "http://www.manutd.com",
"email": "enquiries#manutd.co.uk",
"founded": 1878,
"clubColors": "Red / White",
"venue": "Old Trafford",
"squad": [
{
"id": 3188,
"name": "David De Gea",
"position": "Goalkeeper",
"dateOfBirth": "1990-11-07T00:00:00Z",
"countryOfBirth": "Spain",
"nationality": "Spain",
"shirtNumber": 1,
"role": "PLAYER"
},
{
"id": 3331,
"name": "Marcus Rashford",
"position": "Attacker",
"dateOfBirth": "1997-10-31T00:00:00Z",
"countryOfBirth": "England",
"nationality": "England",
"shirtNumber": 10,
"role": "PLAYER"
},
{
"id": 3372,
"name": "Anthony Martial",
"position": "Attacker",
"dateOfBirth": "1995-12-05T00:00:00Z",
"countryOfBirth": "France",
"nationality": "France",
"shirtNumber": 11,
"role": "PLAYER"
},
{
"id": 3662,
"name": "Romelu Lukaku",
"position": "Attacker",
"dateOfBirth": "1993-05-13T00:00:00Z",
"countryOfBirth": "Belgium",
"nationality": "Belgium",
"shirtNumber": 9,
"role": "PLAYER"
},
If you are using Java 8 or higher, then just iterate over the List first and over the Map in a nested iteration using lambda expressions:
public static void main(String[] args) {
List<Map<String, ?>> jsonList = new ArrayList<>();
Map<String, String> mapOne = new HashMap<String, String>();
mapOne.put("id", String.valueOf(66));
mapOne.put("area", "Some Area");
jsonList.add(mapOne);
jsonList.forEach(map -> {
map.forEach((key, value) -> {
System.out.println(key + ": " + value);
});
});
}
The thing you have to take care of is the String representation of value, since it is a Map<String, ?> in your code and a Map<String, String> in my example, what may lead to problems if you directly use the above example's System.out.println(key + ": " + value);.
First iterate over the list, then iterate over the Map:
for (Map<String, ?> map : allPlayers) {
for (String key : map.keySet()) {
Object player = map.get(key);
// ...
}
}

How to count by attribute in JSON?

I have the following JSON:
{
"items": [
{
"id": "1",
"name": "John",
"location": {
"town": {
"id": "10"
},
"address": "600 Fake Street",
},
"creation_date": "2010-01-19",
"last_modified_date": "2017-05-18"
},
{
"id": "2",
"name": "Sarah",
"location": {
"town": {
"id": "10"
},
"address": "76 Evergreen Street",
},
"creation_date": "2010-01-19",
"last_modified_date": "2017-05-18"
},
{
"id": "3",
"name": "Hamed",
"location": {
"town": {
"id": "20"
},
"address": "50 East A Street",
},
"creation_date": "2010-01-19",
"last_modified_date": "2017-05-18"
}
]
}
And I need to get something like this, count how many times each townId appears:
[ { "10": 2 }, {"20": 1 }]
I'm trying to find the most eficient way to do this. Any idea?
Most efficient way is to load the String in a StringBuilder and remove all line breaks and white spaces. Then search for index of "town":{"id":" string (town start index) and then search for the end index (String `"}'). Using the 2 indexes you can extract town ids and count them.
No need to deserialize the JSON into POJO objects:) and extract values by xpath from the POJOs.

Junit in android for JSON data

I would like to add Junit test for if else statement using assertEquals in android.
My JSON Data
"Main": {
"country": "USA",
"State": "California",
"City": "San Jose"
"Temp" "-10"
},
{
"country": "USA",
"State": "Texas",
"City": "Austin"
"Temp" "10"
},
{
"country": "USA",
"State": "California",
"City": "Cupertino"
"Temp" "00"
},
I am displaying this data base on conditions as below:
if (getTemp!=null && getTemp().getFormatted().startWith("-")) {
displayNegetive.getTemp();
}
else if (getTemp!=null && getTemp().getFormatted().contentEquals("00")) {
displayZero.getTemp();
}
else {
displayPositive.getTemp();
}

Categories