Merge elements of array based on index position or id - java

I have a list array which I'm getting from the database. I want to create a new List with all elements in the array grouped by their index position or id.
This is the array I'm working with:
[
{
"content": "Content A1",
"id": 1
},
{
"content": "Content A2",
"id": 2
},
{
"content": "Content A3",
"id": 3
},
{
"content": "Content A4",
"id": 4
},
{
"content": "Content A5",
"id": 5
}
]
[
{
"content": "Content B1",
"id": 1
},
{
"content": "Content B2",
"id": 2
},
{
"content": "Content B3",
"id": 3
},
{
"content": "Content B4",
"id": 4
},
{
"content": "Content B5",
"id": 5
}
]
[
{
"content": "Content C1",
"id": 1
},
{
"content": "Content C2",
"id": 2
},
{
"content": "Content C3",
"id": 3
},
{
"content": "Content C4",
"id": 4
},
{
"content": "Content C5",
"id": 5
}
]
This is how I want the new List array to look like:
[
{
"content": {"Content A1","Content B1","Content C1"}
"id": 1
},
{
"content": {"Content A2", "Content B2", "Content C2"}
"id": 2
},
{
"content": {"Content A3","Content B3","Content C3"}
"id": 3
},
{
"content": {"Content A4","Content B4","Content C4"}
"id": 4
},
{
"content": {"Content A5","Content B5","Content C5"}
"id": 5
}
]
I have tried this code but it returns only the last object:
List<String> contentArray = new ArrayList<>();
for (int i = 0; i < b.listDetail.size(); i++) {
int finalI = i;
contentArray = listResource.stream()
.map(a -> a.listDetail.get(finalI).content)
.collect(Collectors.toList());
}
System.out.println(contentArray);

You are almost done, just need to store contentArray in a list for all index.
List<List<String>> res = new ArrayList<>();
for (int i = 0; i < b.listDetail.size(); i++) {
int finalI = i;
List<String> contentArray = listResource.stream()
.map(a -> a.listDetail.get(finalI).content)
.collect(Collectors.toList());
res.add(contentArray); // store all contents for a index in list
}
You can create a class for your response with id and contents and construct inside loop and add in the list.

Related

I need the jolt transform for the given input . Photos array is dynamic in nature

If id value is 0 then i don't want that in output. Photos Array is dynamic in nature. Here it is 3 , it can be 3 or 4 or5 any . Your help in this is highly appreciated . thanks .
input JSON
{
"Entity": {
"card": {
"cardNo": "123456789",
"cardStatus": "10",
"cardAddress": "UK",
"cardAddress1": "US",
"cardCity": "mk",
"name": "RAM",
"lastName": "ABU",
"name1": "RAM1",
"lastName1": "ABU1",
"Id1": "0",
"Id2": 0,
"Id3": 0
},
"Photos": [
{
"Id": 327703,
"Caption": "TEST>> photo 1",
"Url": "http://bob.com/0001/327703/photo.jpg"
},
{
"Id": 327704,
"Caption": "TEST>> photo 2",
"Url": "http://bob.com/0001/327704/photo.jpg"
},
{
"Id": 327704,
"Caption": "TEST>> photo 2",
"Url": "http://bob.com/0001/327704/photo.jpg"
}
]
}
}
output JSON
{
"tab": {
"text": "123456789"
},
"address": [
{
"add": "UK",
"add2": "US",
"mk": "mk"
}
],
"Photos": [
{
"caption2": "http.1.com",
"no": "0"
},
{
"caption2": "http.2.com",
"no": "0"
},
{
"caption2": "http.3com",
"no": "0"
},
{
"caption2": "TEST>> photo 1",
"no": "327703"
},
{
"caption2": "TEST>> photo 2",
"no": "327704"
},
{
"caption2": "TEST>> photo 2",
"no": "327704"
}
]
}
expected JSON
{
"tab": {
"text": "123456789"
},
"address": [
{
"add": "UK",
"add2": "US",
"mk": "mk"
}
],
"Photos": [
{
"caption2": "TEST>> photo 1",
"no": "327703"
},
{
"caption2": "TEST>> photo 2",
"no": "327704"
},
{
"caption2": "TEST>> photo 2",
"no": "327704"
}
]
}
jolt spec using
[
{
"operation": "shift",
"spec": {
"Entity": {
"card": {
"cardNo": "tab.text",
"cardAddress": "address[0].add",
"cardAddress1": "address[0].add2",
"cardC*": "address[0].mk",
"Id1": "Photos.no",
"#http.1.com": "Photos.caption2",
"Id2": "Photos.no",
"#http.2.com": "Photos.caption2",
"Id3": "Photos.no",
"#http.3com": "Photos.caption2"
},
"Photos": {
"*": {
"Id": "Photos.no",
"Caption": "Photos.caption2"
}
}
}
}
},
{
"operation": "shift",
"spec": {
"tab": "&",
"address": "&",
"Photos": {
"*": {
"*": {
"#": "&3[&1].&2"
}
}
}
}
},
{
"operation": "modify-overwrite-beta",
"spec": {
"Photos": {
"*": {
"no": "=toString"
}
}
}
}
]
I am thinking one if else logic is required if value is 0 then don't pass otherwise pass like that.
You can start by converting the independent attributes dynamically collect under common nodes, then use conditional logic such as
[
{
"operation": "shift",
"spec": {
"Entity": {
"card": {
"cardNo": "tab.text",
"*Addres*|*City": {
"*": {
"#1": "address[#1].&2"
}
},
"Id*": {// enumerate the members of the object in a dynamical manner
"*": {
"#caption2": "Photos&2[#1].http\\.&(2,1)\\.com", // &(2,1) could be used RHS
"#1": "Photos&2[#1].no"
}
}
},
"*": {
"*": {
"Id": "&2[&1].no", // rename "Id" to "no"
"*": "&2[&1].&"
}
}
}
}
},
{ // combine all objects related to Photoes under common array
"operation": "shift",
"spec": {
"*": "&",
"Photo*": {
"*": {
"#": "Photoes"
}
}
}
},
{ // label objects of photoes by their respective "no" values
"operation": "shift",
"spec": {
"*": "&",
"Photoes": {
"*": {
"http*": {
"$": "&3[&2].#(2,no).#(0)" // exchange key-value pairs
},
"*": "&2[&1].#(1,no).&"
}
}
}
},
{
"operation": "shift",
"spec": {
"*": "&",
"Photoes": {
"*": {
"0": "rem&2", // remPhotoes tagged stuff will be removed
"*": {
"#": "&3[]"
}
}
}
}
},
{
"operation": "remove",
"spec": {
"remPhotoes": ""
}
},
{
"operation": "modify-overwrite-beta",
"spec": {
"Photoes": {
"*": {
"no": "=toString"
}
}
}
}
]
Hey Saurabh I couldn't understand your request properly but this may help you resolve your query. I have created an spec for your expected output, I have kept an if else condition on Photos[].no if its 0 it wont populate the fields, you can check the below spec and input :
Input :
{
"Entity": {
"card": {
"cardNo": "123456789",
"cardStatus": "10",
"cardAddress": "UK",
"cardAddress1": "US",
"cardCity": "mk",
"name": "RAM",
"lastName": "ABU",
"name1": "RAM1",
"lastName1": "ABU1",
"Id1": "0",
"Id2": 0,
"Id3": 0
},
"Photos": [
{
"Id": 0,
"Caption": "TEST>> photo 1",
"Url": "http://bob.com/0001/327703/photo.jpg"
},
{
"Id": 327704,
"Caption": "TEST>> photo 2",
"Url": "http://bob.com/0001/327704/photo.jpg"
},
{
"Id": 327704,
"Caption": "TEST>> photo 2",
"Url": "http://bob.com/0001/327704/photo.jpg"
}
]
}
}
Spec :
[
{
"operation": "shift",
"spec": {
"Entity": {
"card": {
"cardNo": "tab.text",
"cardAddress": "address.[#2].add",
"cardAddress1": "address.[#2].add2",
"cardCity": "address.[#2].mk"
},
"Photos": {
"*": {
"Id": "Photos.[&1].no",
"Caption": "Photos.[&1].caption2"
}
}
}
}
},
{
"operation": "modify-overwrite-beta",
"spec": {
"Photos": {
"*": {
"no": "=toString"
}
}
}
}, {
"operation": "shift",
"spec": {
"*": "&",
"Photos": {
"*": {
"no": {
"0": {
"#(2,no)": "Trash"
},
"*": {
"#(2,no)": "p.Photos.[#4].no",
"#(2,caption2)": "p.Photos.[#4].caption2"
}
}
}
}
}
}, {
"operation": "remove",
"spec": {
"Trash": ""
}
},
{
"operation": "modify-overwrite-beta",
"spec": {
"*": "=recursivelySquashNulls"
}
},
{
"operation": "shift",
"spec": {
"*": "&",
"p": {
"Photos": "Photos"
}
}
}
]
You may consider another library Josson to do the same job by shorter transformation statement.
https://github.com/octomix/josson
Deserialization
Josson josson = Josson.fromJsonString(
"{" +
" \"Entity\": {" +
" \"card\": {" +
" \"cardNo\": \"123456789\"," +
" \"cardStatus\": \"10\"," +
" \"cardAddress\": \"UK\"," +
" \"cardAddress1\": \"US\"," +
" \"cardCity\": \"mk\"," +
" \"name\": \"RAM\"," +
" \"lastName\": \"ABU\"," +
" \"name1\": \"RAM1\"," +
" \"lastName1\": \"ABU1\"," +
" \"Id1\": \"0\"," +
" \"Id2\": 0," +
" \"Id3\": 0" +
" }," +
" \"Photos\": [" +
" {" +
" \"Id\": 0," +
" \"Caption\": \"TEST>> photo 1\"," +
" \"Url\": \"http://bob.com/0001/327703/photo.jpg\"" +
" }," +
" {" +
" \"Id\": 327704," +
" \"Caption\": \"TEST>> photo 2\"," +
" \"Url\": \"http://bob.com/0001/327704/photo.jpg\"" +
" }," +
" {" +
" \"Id\": 327704," +
" \"Caption\": \"TEST>> photo 2\"," +
" \"Url\": \"http://bob.com/0001/327704/photo.jpg\"" +
" }" +
" ]" +
" }" +
"}");
Transformation
JsonNode node = josson.getNode(
"Entity.map(" +
" tab: map(text: card.cardNo)," +
" address: wrap(card.map(" +
" add: cardAddress," +
" add2: cardAddress1," +
" cardCity:: cardCity))," +
" Photos[Id!=0]*.map(" +
" caption2: Caption," +
" no: toText(Id))" +
")");
System.out.print(node.toPrettyString());
Output
{
"tab" : {
"text" : "123456789"
},
"address" : [ {
"add" : "UK",
"add2" : "US",
"mk" : "mk"
} ],
"Photos" : [ {
"caption2" : "TEST>> photo 2",
"no" : "327704"
}, {
"caption2" : "TEST>> photo 2",
"no" : "327704"
} ]
}

change name of property in a list to list nested json using JOLT

I am news to jolt json transformation. So looking for help in transforming nested json having list of values to nested json with list as following.
Input json
{
"userData": [
{
"userId": "1",
"age": "20",
"firstName": "firstname1",
"lastname": "lastname1",
"zipCode": "zipcode1",
"street": "street1",
"city": "city1",
"country": "country",
"gender": "gender1",
"grade": "grade1",
"birthday": "birthday1"
},
{
"userId": "2",
"age": "25",
"firstName": "firstname2",
"lastname": "lastname2",
"zipCode": "zipcode2",
"street": "street2",
"city": "city2",
"country": "country2",
"gender": "gender2",
"grade": "grade2",
"birthday": "birthday2"
}
]
}
Jolt Specification
[
{
"operation": "shift",
"spec": {
"userData": {
"*": {
"userId": "data.[&1].ID",
"*": "data.[&1].&",
"zipCode": {
"#custom-field1": "adr_&1.property",
"#": "adr_&.value"
},
"street": {
"#custom-field2": "adr_&1.property",
"#": "adr_&.value"
},
"city": {
"#custom-field3": "adr_&1.property",
"#": "adr_&.value"
},
"country": {
"#custom-field4": "adr_&1.property",
"#": "adr_&.value"
}
}
}
}
}
]
Output
{
"data" : [ {
"ID" : "1",
"age" : "20",
"firstName" : "firstname1",
"lastname" : "lastname1",
"gender" : "gender1",
"grade" : "grade1",
"birthday" : "birthday1"
}, {
"ID" : "2",
"age" : "25",
"firstName" : "firstname2",
"lastname" : "lastname2",
"gender" : "gender2",
"grade" : "grade2",
"birthday" : "birthday2"
} ],
"adr_zipCode" : {
"property" : [ "custom-field1", "custom-field1" ],
"value" : [ "zipcode1", "zipcode2" ]
},
"adr_street" : {
"property" : [ "custom-field2", "custom-field2" ],
"value" : [ "street1", "street2" ]
},
"adr_city" : {
"property" : [ "custom-field3", "custom-field3" ],
"value" : [ "city1", "city2" ]
},
"adr_country" : {
"property" : [ "custom-field4", "custom-field4" ],
"value" : [ "country", "country2" ]
}
}
Expected json
{
"data": [
{
"ID": "1",
"age": "20",
"firstName": "firstname1",
"lastname": "lastname1",
"gender": "gender1",
"grade": "grade1",
"birthday": "birthday1",
"address": [
{
"property": "custom-field1",
"value": "zipcode1"
},
{
"property": "custom-field2",
"value": "street1"
},
{
"property": "custom-field3",
"value": "city1"
},
{
"property": "custom-field4",
"value": "country"
}
]
},
{
"ID": "2",
"age": "25",
"firstName": "firstname2",
"lastname": "lastname2",
"gender": "gender2",
"grade": "grade2",
"birthday": "birthday2",
"address": [
{
"property": "custom-field1",
"value": "zipcode2"
},
{
"property": "custom-field2",
"value": "street2"
},
{
"property": "custom-field3",
"value": "city2"
},
{
"property": "custom-field4",
"value": "country2"
}
]
}
]
}
You can use individual value arrays of their indexes to be used within the upcoming specs with a tricky zeroth member which will be removed later, after been used such as
[
{
"operation": "shift",
"spec": {
"userData": {
"*": {
"userId": "data[&1].ID",
"#(0,age)": "data[&1].age", //multiplexed this attribute in order to make it the zeroth index, which will be removed within the upcoming specs, for the "address" array at the same time, as indexing starts from zero ...
"*": "data[&1].&",
"a*|z*|s*|c*": {//separating "zipCode", "street", "city", "country" attributes from the others while using "a*" for "age" is tricky, temporarily
"#": "data[&2].value"
}
}
}
}
},
{
"operation": "shift",
"spec": {
"data": {
"*": {
"*": "&2[&1].&",
"value": {
"*": {
"#property": "&4[&3].address[&1].custom-field&1",
"#(2,value[&])": "&4[&3].address[&1].value"
}
}
}
}
}
},
{ // the attributes are written individually to keep the desired sorting
"operation": "shift",
"spec": {
"data": {
"*": {
"ID": "&2[&1].&",
"age": "&2[&1].&",
"firstName": "&2[&1].&",
"lastname": "&2[&1].&",
"gender": "&2[&1].&",
"grade": "&2[&1].&",
"birthday": "&2[&1].&",
"address": {
"0": "&4[&3].&2[&1]",
"*": {
"*": {
"$": "&5[&4].&3[&2].#(0)" // key-value pairs are exchanged for this attribute
},
"value": "&4[&3].&2[&1].&"
}
}
}
}
}
},
{ // get rid of null components of the array
"operation": "modify-overwrite-beta",
"spec": {
"*": "=recursivelySquashNulls"
}
}
]
[
{
"operation": "shift",
"spec": {
"userData": {
"*": {
"userId": "data.[&1].ID",
"*": "data.[&1].&",
"zipCode": {
"#custom-field1": "data[#3].address[#2].property",
"#": "data[#3].address[#2].value"
},
"street": {
"#custom-field2": "data[#3].address[#2].property",
"#": "data[#3].address[#2].value"
},
"city": {
"#custom-field3": "data[#3].address[#2].property",
"#": "data[#3].address[#2].value"
},
"country": {
"#custom-field4": "data[#3].address[#2].property",
"#": "data[#3].address[#2].value"
}
}
}
}
},
{ // get rid of null components of the array
"operation": "modify-overwrite-beta",
"spec": {
"*": "=recursivelySquashNulls"
}
}
]
You may consider another library Josson to do the same job by shorter transformation statement.
https://github.com/octomix/josson
Deserialization
Josson josson = Josson.fromJsonString(
"{" +
" \"userData\": [" +
" {" +
" \"userId\": \"1\"," +
" \"age\": \"20\"," +
" \"firstName\": \"firstname1\"," +
" \"lastname\": \"lastname1\"," +
" \"zipCode\": \"zipcode1\"," +
" \"street\": \"street1\"," +
" \"city\": \"city1\"," +
" \"country\": \"country\"," +
" \"gender\": \"gender1\"," +
" \"grade\": \"grade1\"," +
" \"birthday\": \"birthday1\"" +
" }," +
" {" +
" \"userId\": \"2\"," +
" \"age\": \"25\"," +
" \"firstName\": \"firstname2\"," +
" \"lastname\": \"lastname2\"," +
" \"zipCode\": \"zipcode2\"," +
" \"street\": \"street2\"," +
" \"city\": \"city2\"," +
" \"country\": \"country2\"," +
" \"gender\": \"gender2\"," +
" \"grade\": \"grade2\"," +
" \"birthday\": \"birthday2\"" +
" }" +
" ]" +
"}");
Transformation
JsonNode node = josson.getNode(
"map(data:userData" +
" .field(ID:userId, userId:," +
" zipCode:, street:, city:, country:," +
" address:collect(" +
" map(property:'customer-field1',value:zipCode)," +
" map(property:'customer-field2',value:street)," +
" map(property:'customer-field3',value:city)," +
" map(property:'customer-field4',value:country))))");
System.out.print(node.toPrettyString());
Output
{
"data" : [ {
"age" : "20",
"firstName" : "firstname1",
"lastname" : "lastname1",
"gender" : "gender1",
"grade" : "grade1",
"birthday" : "birthday1",
"ID" : "1",
"address" : [ {
"property" : "customer-field1",
"value" : "zipcode1"
}, {
"property" : "customer-field2",
"value" : "street1"
}, {
"property" : "customer-field3",
"value" : "city1"
}, {
"property" : "customer-field4",
"value" : "country"
} ]
}, {
"age" : "25",
"firstName" : "firstname2",
"lastname" : "lastname2",
"gender" : "gender2",
"grade" : "grade2",
"birthday" : "birthday2",
"ID" : "2",
"address" : [ {
"property" : "customer-field1",
"value" : "zipcode2"
}, {
"property" : "customer-field2",
"value" : "street2"
}, {
"property" : "customer-field3",
"value" : "city2"
}, {
"property" : "customer-field4",
"value" : "country2"
} ]
} ]
}

Get JSON value and store it

Here is my JSON file, I need to take values from key : value pair and then thoose values to store into ArrayList rating to sort it, but with this code I just get "reviews" as the key ... Can you help me? I know to get all key : value pairs but i need just one pair and take value from it. Should I use Iterator, for each ? Can you give me some direction and example
{
"reviews": [
{
"id": 2097047,
"reviewId": "93f131be27dc1122bb7ef0048ad10e4f",
"reviewFullText": "5 star review",
"reviewText": "5 star review",
"numLikes": 0,
"numComments": 0,
"numShares": 0,
"rating": 5,
"reviewCreatedOn": "2 months ago",
"reviewCreatedOnDate": "2021-01-25T13:00:35+00:00",
"reviewCreatedOnTime": 1611579635,
"reviewerId": null,
"reviewerUrl": null,
"reviewerName": "Reviewer #20",
"reviewerEmail": null,
"sourceType": "custom",
"isVerified": false,
"source": "custom",
"sourceName": "1-20 Reviews",
"sourceId": "890cdd7974cdf8aabe6e9051f5a87303bdb933ae",
"tags": [],
"href": null,
"logoHref": null,
"photos": []
},
{
"id": 2097046,
"reviewId": "6e7bd4c71a56885ef583bd79186af689",
"reviewFullText": "4 star review",
"reviewText": "4 star review",
"numLikes": 0,
"numComments": 0,
"numShares": 0,
"rating": 4,
"reviewCreatedOn": "2 months ago",
"reviewCreatedOnDate": "2021-01-25T13:00:21+00:00",
"reviewCreatedOnTime": 1611579621,
"reviewerId": null,
"reviewerUrl": null,
"reviewerName": "Reviewer #19",
"reviewerEmail": null,
"sourceType": "custom",
"isVerified": false,
"source": "custom",
"sourceName": "1-20 Reviews",
"sourceId": "890cdd7974cdf8aabe6e9051f5a87303bdb933ae",
"tags": [],
"href": null,
"logoHref": null,
"photos": []
},
public class GetPair {
public static void main(String[] args) throws FileNotFoundException, IOException, ParseException {
ArrayList<Object> rating = new ArrayList<>();
Object obj = new JSONParser()
.parse(new FileReader("C:\\Users\\User\\eclipse-workspace\\Task\\files\\reviews.json"));
JSONObject jo = (JSONObject) obj;
for (Object key : jo.keySet()) {
String keys = (String) key;
Object keyObj = jo.get(keys);
if (!(keyObj instanceof JSONObject)) {
// System.out.println(keys + " " + keyObj);
}
rating.add(keys);
System.out.println(rating);
}
}
}
The main object only has one key: "reviews". Its value is an array. If you want to add each element of the array in the ArrayList, you can do something like this:
JSONObject jo = (JSONObject) obj;
JSONArray array = (JSONArray)jo.get("reviews");
for (int ix = 0; ix < array.size(); ++ix) {
JSONObject elm = (JSONObject)array.get(ix);
rating.add(elm);
System.out.println(rating);
}

How to traverse through inner Json array and retrieve the values

I have an response Json given below I need to retrieve the values of price from inner "childItems" Array and sum it up to get the total price = 7.7
Below is the java code i just tried with which I guess is bit wrong.
List<Float> items_price = response.jsonPath().getList("items.childItems.price");
float Total_Price=0;
for(int i=0;i<items_price.size();i++)
{
Total_Price = Total_Price + items_price.get(i);
}
Total_Price = Total_Price + response.jsonPath().getFloat("tax");
Below is the Response Json
==========================
{
"brandId": "HAL",
"sellingChannel": "WEBOA",
"subTotal": 7.19,
"total": 7.7,
"items": [
{
"lineItemId": 101,
"description": "Apple Buffet",
"price": 0,
"priceType": null,
"productId": "HAL-itm-000-057",
"childItems": [
{
"lineItemId": 102,
"description": "Apple",
"price": 3.31,
"priceType": null,
"productId": "HAL-itm-000-055",
"childItems": [],
"modifierGroups": [
{
"description": null,
"productId": "HAL-prg-001-001",
"modifiers": [
{
"productId": "HAL-itm-006-011",
"price": 2,
"priceType": null,
"actionCode": null,
"quantity": 1
}
]
},
{
"description": null,
"productId": "HAL-prg-001-002",
"modifiers": []
},
{
"description": null,
"productId": "HAL-prg-001-003",
"modifiers": [
{
"productId": "HAL-itm-008-011",
"price": 0.29,
"priceType": null,
"actionCode": null,
"quantity": 1
},
{
"productId": "HAL-itm-008-004",
"price": 0,
"priceType": null,
"actionCode": null,
"quantity": 1
},
{
"productId": "HAL-itm-008-005",
"price": 0.29,
"priceType": null,
"actionCode": null,
"quantity": 1
}
]
},
{
"description": null,
"productId": "HAL-prg-001-004",
"modifiers": [
{
"productId": "HAL-itm-009-013",
"price": 0,
"priceType": null,
"actionCode": null,
"quantity": 1
}
]
},
{
"description": null,
"productId": "HAL-prg-001-005",
"modifiers": []
},
{
"description": null,
"productId": "HAL-prg-001-006",
"modifiers": []
},
{
"description": null,
"productId": "HAL-prg-001-008",
"modifiers": [
{
"productId": "HAL-itm-013-007",
"price": 0,
"priceType": null,
"actionCode": null,
"quantity": 1
}
]
},
{
"description": null,
"productId": "HAL-prg-001-010",
"modifiers": [
{
"productId": "HAL-itm-015-001",
"price": 0,
"priceType": null,
"actionCode": null,
"quantity": 1
}
]
}
],
"quantity": 1,
"note": null
},
{
"lineItemId": 103,
"description": "Vegetable Fires",
"price": 1.99,
"priceType": null,
"productId": "HAL-itm-002-002",
"childItems": [],
"modifierGroups": [
{
"description": null,
"productId": "HAL-prg-001-006",
"modifiers": []
},
{
"description": null,
"productId": "HAL-prg-001-005",
"modifiers": []
}
],
"quantity": 1,
"note": null
},
{
"lineItemId": 104,
"description": "Coca-Cola®",
"price": 1.89,
"priceType": null,
"productId": "HAL-itm-003-001",
"childItems": [],
"modifierGroups": [
{
"description": null,
"productId": "HAL-prg-001-011",
"modifiers": [
{
"productId": "HAL-itm-016-001",
"price": 0,
"priceType": null,
"actionCode": null,
"quantity": 1
}
]
},
{
"description": null,
"productId": "HAL-prg-001-012",
"modifiers": [
{
"productId": "HAL-itm-017-001",
"price": 0,
"priceType": null,
"actionCode": null,
"quantity": 1
}
]
}
],
"quantity": 1,
"note": null
}
],
"modifierGroups": [],
"quantity": 1,
"note": null
}
],
"fulfillment": {
"fulfillmentType": "TimePickup",
"asap": true,
"pickupTime": null,
"storeLocation": {
"locationId": "99983"
}
},
"tallyTime": "2018-03-25T12:41:29.949Z",
"tax": 3.51
}
Please let me know your thoughts on this. Thanks in advance.
Just tried the below approach and it worked for me.
JSONObject results = new JSONObject(response.asString());
JSONArray childItems= results.getJSONArray("items").getJSONObject(0).getJSONArray("childItems");
float Total_Price =0;
for(int i=0;i<childItems.length();i++)
{
//scenario.write(childItems.toString());
scenario.write(+i +" : "+childItems.getJSONObject(i).getFloat("price"));
Total_Price = Total_Price + childItems.getJSONObject(i).getFloat("price");
}
Total_Price = Total_Price + response.jsonPath().getFloat("tax");
Assert.assertEquals(Total_Price, response.jsonPath().getFloat("total"),"Total Price in response is not equal to sum of line items price plus tax");

Access single value of Jsonarray [duplicate]

This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 7 years ago.
I used the code to get a Jsonarray
JSONArray preferenceobj = (JSONArray) personobj.get("preferences");
The a json array like this code bellow. How can I get individual value of ratings.
[{
"rating": 3,
"documentId": "TRECCS-00674898-160",
"tags": ["Romantic", "Seafood", "Family Friendly"]
}, {
"rating": 2,
"documentId": "TRECCS-00247656-160",
"tags": ["Bar-hopping"]
}, {
"rating": 3,
"documentId": "TRECCS-00085961-160",
"tags": ["Gourmet Food"]
}, {
"rating": 4,
"documentId": "TRECCS-00086637-160",
"tags": ["Family Friendly", "Local Food", "Entertainment"]
}, {
"rating": 4,
"documentId": "TRECCS-00086308-160",
"tags": ["Family Friendly", "Tourism"]
}, {
"rating": 4,
"documentId": "TRECCS-00086622-160",
"tags": ["Healthy Food", "Romantic", "Gourmet Food"]
}, {
"rating": 2,
"documentId": "TRECCS-00809111-160",
"tags": ["Wellness", "Family Friendly", "Sport"]
}, {
"rating": 4,
"documentId": "TRECCS-00086310-160",
"tags": ["Family Friendly", "Sport"]
}, {
"rating": 4,
"documentId": "TRECCS-00340169-160",
"tags": ["Fashion Bargains", "Live Music", "Shopping for accessories", "Family Friendly"]
}, {
"rating": 4,
"documentId": "TRECCS-00018110-160",
"tags": ["Healthy Food", "Family Friendly", "Local Food", "Organic Food"]
}, {
"rating": 2,
"documentId": "TRECCS-00085880-160",
"tags": ["Romantic", "Sailing", "Seafood"]
}, {
"rating": 4,
"documentId": "TRECCS-00259825-152",
"tags": ["Family Friendly", "Budget Friendly"]
}]
Use this:
JSONArray preferenceobj = (JSONArray) personobj.get("preferences");
List<Integer> ratings = new ArrayList<>();
for(int i = 0; i < preferenceobj.length(); i++) {
JSONObject obj = preferenceobj.getJSONObject(i);
int rating = obj.getInt("rating"); // Your rating
ratings.add(rating);
}
// Show ratings
for(Integer rating : ratings) {
System.out.println(rating);
}
The answer I solved using the prvious comment of Srarta is:
JSONArray preferenceobj = (JSONArray) personobj.get("preferences");
List<Long> ratings = new ArrayList<>();
for(int i = 0; i < preferenceobj.size(); i++) {
JSONObject obj1 = (JSONObject) preferenceobj.get(i);
Long rating = (Long)obj1.get("rating");
ratings.add(rating);
}
// Show ratings
for(Long rating : ratings) {
System.out.println(rating);
}

Categories