Access single value of Jsonarray [duplicate] - java

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);
}

Related

Java Json Repeating the key

I have a problem always i call the method addplayers he inserts into the jsonfile the array required, but, he always create new key , so, i'm trying to insert a new player in the key Players always i create a new player.
I created some conditions for that but is not working, like parsing the file and check the key.
the expecteded result:
{
"players": [
{
"current_Energy": 100,
"level": 1,
"name": "tenente",
"experiencePoints": 0,
"team": "Giants"
},
{
"current_Energy": 100,
"level": 1,
"name": "tenente",
"experiencePoints": 0,
"team": "Giants"
},
{
"current_Energy": 100,
"level": 1,
"name": "tenente",
"experiencePoints": 0,
"team": "Giants"
}
]
}
the result at moment:
{
"players": [
{
"current_Energy": 100,
"level": 1,
"name": "tenente",
"experiencePoints": 0,
"team": "Giants"
},
{
"current_Energy": 100,
"level": 1,
"name": "tenente",
"experiencePoints": 0,
"team": "Giants"
},
{
"current_Energy": 100,
"level": 1,
"name": "tenente",
"experiencePoints": 0,
"team": "Giants"
}
]
}
{
"players": [
{
"current_Energy": 100,
"level": 1,
"name": "tenente",
"experiencePoints": 0,
"team": "Giants"
},
{
"current_Energy": 100,
"level": 1,
"name": "tenente",
"experiencePoints": 0,
"team": "Giants"
},
{
"current_Energy": 100,
"level": 1,
"name": "tenente",
"experiencePoints": 0,
"team": "Giants"
}
]
}
The Method
public void addPlayer(PlayerManager playerManager) {
if (file.exists()) {
System.out.println("FODASEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE");
try {
PrintStream printStream = new PrintStream(new FileOutputStream("data.json",true));
JSONObject jsonObject = new JSONObject();
JSONArray jsonArray;
ArrayUnorderedList<Players> dataplayer = playerManager.getPlayersList();
try {
jsonObject = (JSONObject) new JSONParser().parse(new FileReader(file));
jsonArray = (JSONArray) jsonObject.get("players");
} catch (ParseException e) {
// Caso não exista, cria um novo objeto JSON com a chave "players"
jsonArray = new JSONArray();
}
Set<String> keys = new HashSet<>();
if (jsonObject.containsKey("players")) {
keys.add("players");
}
if (!keys.contains("players")) {
jsonArray = new JSONArray();
jsonObject.put("players", jsonArray);
} else {
jsonArray = (JSONArray) jsonObject.get("players");
}
for (Players player : dataplayer) {
JSONObject playerObject = new JSONObject();
playerObject.put("name", player.getName());
playerObject.put("team", player.getTeam().toString());
playerObject.put("level", player.getLevel());
playerObject.put("experiencePoints", player.getExperiencePoints());
playerObject.put("current_Energy", player.getCurrentEnergy());
jsonArray.add(playerObject);
}
printStream.println(jsonObject);
printStream.flush();
printStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
At a glance the problem seems to be that you're reading and changing the same file, which you have open in append mode:
PrintStream printStream = new PrintStream(new FileOutputStream("data.json",true));
The true parameter there means whatever you write on that file will be appended at the end when you write to it, which seems compatible with the behaviour you're seeing.
Depending on what you need to achieve, you might prefer to just write on a different file as output.

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");

i want to show value arraylist in arraylist javaspring, how to fix it?

My code
public List<PaymentDetailInfo> PaymentDetailsInfo(List<Transaction> transactionInfo) {
List<PaymentDetailInfo> result = new ArrayList<>();
PaymentDetailInfo pay = new PaymentDetailInfo();
List<PaymentDetailProduct> detProd = new ArrayList<>();
PaymentDetailProduct det = new PaymentDetailProduct();
for (int i = 0; i < transactionInfo.size(); i++) {
pay.setTransactionId(transactionInfo.get(i).getTransactionId());
pay.setYourPayment(transactionInfo.get(i).getYourPayment() == null ? 0 : transactionInfo.get(i).getYourPayment());
pay.setSisaPembayaran(transactionInfo.get(i).getSisaPembayaran() == null ? 0 : transactionInfo.get(i).getSisaPembayaran());
pay.setDendaKeterlambatan(transactionInfo.get(i).getDendaKeterlambatan() == null ? 0 : transactionInfo.get(i).getDendaKeterlambatan());
pay.setJatuhTempo(transactionInfo.get(i).getJatuhTempo() == null ? "" : transactionInfo.get(i).getJatuhTempo());
pay.setTotalPembayaran(transactionInfo.get(i).getTotalPembayaran() == null ? 0 : transactionInfo.get(i).getTotalPembayaran());
for(int j = 0; j<transactionInfo.get(i).getMerchantProduct().size(); j++){
det.setProductId(transactionInfo.get(i).getMerchantProduct().iterator().next().getMerchantProductId());
det.setProductName(transactionInfo.get(i).getMerchantProduct().iterator().next().getProductName());
det.setProductPrice(transactionInfo.get(i).getMerchantProduct().iterator().next().getProductPrice());
det.setRegisteredDate(transactionInfo.get(i).getMerchantProduct().iterator().next().getCreatedDate());
det.setLastModified(transactionInfo.get(i).getMerchantProduct().iterator().next().getUpdatedDate());
detProd.add(det);
pay.setPaymentProduct(detProd);
}
pay.setRegisteredDate(DateUtils.formatDateTimeOrEmptyString(transactionInfo.get(i).getCreatedDate()));
pay.setLastModified(DateUtils.formatDateTimeOrEmptyString(transactionInfo.get(i).getUpdatedDate()));
result.add(pay);
}
return result;
}
{
"meta": {
"code": "2000",
"message": "Sukses"
},
"data": {
"detailPayment": {
"fin_payment": {
"financialName": "BCAFINANCE",
"loanLimit": 10000000,
"sisaLimit": 7900000,
"loanId": "61929149-59f4-4f2e-9ffd-7bbc6370fdaf",
"registeredDate": "06/01/2021 22:20",
"lastModified": "07/Jan/2021 03:03"
},
"det_payment": [
{
"transactionId": "09699913-e006-4684-b1e3-a346991609bd",
"yourPayment": 0,
"sisaPembayaran": 0,
"dendaKeterlambatan": 0,
"jatuhTempo": "",
"paymentProduct": [
{
"productId": "39c3cfdb-5e76-45c3-b0a1-d96d0181a73c",
"productName": "BAJU",
"productPrice": 350000,
"registeredDate": "2021-01-06T22:50:41.270955"
},
{
"productId": "39c3cfdb-5e76-45c3-b0a1-d96d0181a73c",
"productName": "BAJU",
"productPrice": 350000,
"registeredDate": "2021-01-06T22:50:41.270955"
},
{
"productId": "39c3cfdb-5e76-45c3-b0a1-d96d0181a73c",
"productName": "BAJU",
"productPrice": 350000,
"registeredDate": "2021-01-06T22:50:41.270955"
},
{
"productId": "39c3cfdb-5e76-45c3-b0a1-d96d0181a73c",
"productName": "BAJU",
"productPrice": 350000,
"registeredDate": "2021-01-06T22:50:41.270955"
},
{
"productId": "39c3cfdb-5e76-45c3-b0a1-d96d0181a73c",
"productName": "BAJU",
"productPrice": 350000,
"registeredDate": "2021-01-06T22:50:41.270955"
}
],
"totalPembayaran": 0,
"registeredDate": "",
"lastModified": ""
},
{
"transactionId": "09699913-e006-4684-b1e3-a346991609bd",
"yourPayment": 0,
"sisaPembayaran": 0,
"dendaKeterlambatan": 0,
"j

Merge elements of array based on index position or id

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.

Categories