I have json and there is array of 'products'.
{
"data": [
{
"contact_id": "...",
"email": "...",
"first_name": "...",
"hash_campaign": "",
"hash_campaign_valid_to_date": null,
"hash_password": "",
"last_name": "...",
"loans": [
],
"max_available_loan_amount": 2000.00,
"middle_name": "P",
"mobile": "...",
"personal_id": "...",
"product_code": 2,
"products": [
{
"available_loan_terms": [
15,
21,
30,
7,
45
],
"default_amount": 0,
"default_term": 15,
"document_required": 0,
"max_available_loan_amount": 2000.00,
"max_loan_amount": 0,
"max_monthly_payment": 0.00,
"product_code": 2
},
{
"available_loan_terms": [
3,
6,
4,
5
],
"default_amount": 0,
"default_term": 0,
"document_required": 0,
"max_available_loan_amount": 4000.00,
"max_loan_amount": 0,
"max_monthly_payment": 1300.00,
"product_code": 101
},
{
"available_loan_terms": [
3,
6,
4,
5
],
"default_amount": 0,
"default_term": 0,
"document_required": 0,
"max_available_loan_amount": 3000.00,
"max_loan_amount": 0,
"max_monthly_payment": 1510.00,
"product_code": 100
}
],
"scoring_through_zoral": "0"
}
],
"description": "...",
"requestId": "...",
"status": 8888
}
I would like to get values of fields 'default_term' and 'max_available_loan_amount' only for product with code 2.
I use restassured
I've tried
List<List> lists = response.body().jsonPath().getList("data.products");
but this code returns list with only one item, I mean all products in one item...
how can I get information for first item in products array from this json ???
Step 1: Create POJO to mapping
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
#Data
#JsonIgnoreProperties(ignoreUnknown = true)
public static class Product {
#JsonProperty("default_term")
private int default_term;
#JsonProperty("max_available_loan_amount")
private double max_available_loan_amount;
}
Step 2: Extract response and deserialize to object.
Product product = ...jsonPath().getObject("data[0].products.find {it.product_code == 2}", Product.class);
System.out.println(product);
//Product(default_term=15, max_available_loan_amount=2000.0)
This could work
List<Integer> li_defaultTerm = response.getBody().jsonPath().get("$..products[?(#.product_code=='2')].default_term");
System.out.println(li_defaultTerm.get(0));
//15
List<Double> li_MaxAvailLoanAmount = response.getBody().jsonPath().get("$..products[?(#.product_code=='2')].max_available_loan_amount");
System.out.println(li_MaxAvailLoanAmount.get(0));
//2000.0
Related
Alrighty I've been banging my head in a wall whole day and cant solve this issue. I am trying to find an id in a object list which is like 3 levels down the hierarchy with java stream. I know how to do it with for loop but I need to get it with stream.
json response is
"NumberOfOwners": 1,
"CurrentPage": 1,
"TotalItems": 1,
"TotalPages": 1,
"PageSize": 1,
"PageItems": [
{
"Id": 1560,
"Title": "PlsWrk",
"IsSubmitted": true,
"Owner": {
"Branch": null,
"Position": null,
"Id": null,
"FirstName": null,
"LastName": null,
"ParentName": null,
"Gender": null,
"Image": null,
"LoginStatusId": 0,
"EmployeeStatus": 0,
"CompanyName": null,
"IsSubcontractor": false
},
"KeyResults": [
{
"Id": 5032,
"Title": "asdf1",
"OverallStatus": 2,
"MonthKeyResults": [
{
"Id": 12484,
"Month": 9,
"Status": 3,
"Progress": "REaplace1"
},
{
"Id": 12483,
"Month": 8,
"Status": 3,
"Progress": "sadf4"
},
{
"Id": 12482,
"Month": 7,
"Status": 1,
"Progress": "On Track1"
}
]
},
{
"Id": 5033,
"Title": "asdf2",
"OverallStatus": 1,
"MonthKeyResults": [
{
"Id": 12485,
"Month": 7,
"Status": 2,
"Progress": "Recovery2"
},
{
"Id": 12487,
"Month": 9,
"Status": 2,
"Progress": "asdfreas"
},
{
"Id": 12486,
"Month": 8,
"Status": 1,
"Progress": "asdf5"
}
]
},
{
"Id": 5034,
"Title": "asdf3",
"OverallStatus": 2,
"MonthKeyResults": [
{
"Id": 12490,
"Month": 9,
"Status": 1,
"Progress": "asdafa"
},
{
"Id": 12489,
"Month": 8,
"Status": 2,
"Progress": "asdf6"
},
{
"Id": 12488,
"Month": 7,
"Status": 3,
"Progress": "Replace3"
}
]
}
]
}
]
Precisely I want stream to return MonthyKeyResult object with a specific id
Atm I am here
public static MonthKeyResults getOkrMonthlyProgressById(PageItems okr, Integer monthlyProgressId){
//here i get KeyResults object list
List<KeyResults> keyResult = okr.getKeyResults().stream().collect(Collectors.toList());
//and now I am trying to get all MonthKeyResults
//objects but I not doing it right
List<MonthKeyResults> monthKeyResults = keyResult.stream().
filter(monthKeyResult -> monthKeyResult.
getMonthKeyResults().
stream().collect(Collectors.toList()));
//and then I am thinking of going trough the monthKeyResults
//list with stream and finding Id I need and returning that
//whole object with something like this
MonthKeyResults mKeyResults = monthKeyResults.stream().filter(id -> id.getId().
equals(monthlyProgressId)).findAny().orElse(null);
return mKeyResult
}
I got one more question
I've separated getting the final object as you see in 3 streams, is it possible to get it in one go or you need to separate this objects like this and go trough them separately?
Probably you're looking for something like:
return okr.getKeyResults().stream()
.flatMap(keyResult -> keyResult.getMonthKeyResults().stream())
.filter(monthKeyResult -> monthKeyResult.getId().equals(monthlyProgressId))
.findAny()
.orElse(null);
Edit: fixed typo.
orderHDRObjectList contains hdrObject table deatils and orderDETObjList contains orderDetails table list
this is a valid jason and i want to implement this.
and display orderHdrObjList of orderId=1 and corresponding orderDETObjList of orderId=1 and so on..
how can I do that?
{
"orderObj": {
"orderHDRObjList": {
"hdrObject": [{
"orderID": 1,
"customerName": "Alex",
"address": "Kottayam",
"totalPrice": 250,
"orderDate": "2020-11-21"
},
{
"orderID": 2,
"customerName": "Aljin",
"address": "Kochi",
"totalPrice": 250,
"orderDate": "2020-11-21"
}
]
},
"orderDETObjList": {
"1": [{
"productId": 2,
"productQty": 250,
"price": 500
},
{
"productId": 3,
"productQty": 150,
"price": 300
}
],
"2": [{
"productId": 2,
"productQty": 250,
"price": 500
},
{
"productId": 3,
"productQty": 150,
"price": 300
}
]
}
}
}
solution 1: use jackson explained here for converting your model to json: Converting Java objects to JSON with Jackson
solution 2:
use java classes: JSONObject and JSONArray
*needs
import org.json.JSONArray;
import org.json.JSONObject;
e.g:
JSONObject json = new JSONObject();
json.put("key1", "value1");
JSONArray array = new JSONArray();
array.put(1);
array.put(2);
json.put("numbers", array);
the output will be this
{
"key1": "value1",
"numbers": [
1,
2
]
}
to convert your java json object to a string use toString() method
System.out.println(json.toString());
some IDEs like IntelliJ suggests to put your json codes inside a try...catch because it may produce some Exceptions when you want to read data with a wrong index.
I get data from an API in which the JSON object changes randomly, like if it is at "position": 1, now it will change randomly to "number": 1. So, how can I check in my application if the object is at "position": 1 or "number": 1 and use it as int?
JSON :-
{
"now": [{
"time": {
"starts_in": 0,
"ends_in": 79580,
"starts_at": 0,
"ends_at": "2018-01-21T08:00:00.788Z"
},
"coins": {
"free": 8,
"first_win": 16,
"max": 52,
"collected": 0
},
"unk1": -88317689,
"position": 1,
"xp_multiplier": 0,
"location_scid": {
"scid_type": 15,
"scid_id": 1
},
"tid": "TID_WANTED_3",
"location": "Terre",
"mode": {
"name": "Bty",
"color": "#0884FA",
"description": " The team wins!"
},
"unk4": 0,
"info": "",
"unk5": 0,
"unk6": 0
}, {
"time": {
"starts_in": 0,
"ends_in": 36380,
"starts_at": 0,
"ends_at": "2018-01-20T20:00:00.788Z"
},
"coins": {
"free": 24,
"first_win": 0,
"max": 32,
"collected": 0
}
}],
"later": [{
"time": {
"starts_in": 79580,
"ends_in": 165980,
"starts_at": "2018-01-21T08:00:00.788Z",
"ends_at": "2018-01-22T08:00:00.788Z"
},
"coins": {
"free": 8,
"first_win": 16,
"max": 52,
"collected": 0
},
"unk1": -88217689,
"position": 1,
"xp_multiplier": 0,
"location_scid": {
"scid_type": 15,
"scid_id": 7
},
"tid": "TID_GOLDRUSH_1",
"location": "Mine",
"mode": {
"name": "Grab",
"color": "#AA57CF",
"description": " An. "
}
}]
}
Thanks in advance :)
JSONObject c = //Your jsonObject;
String position = c.getInt("position");
String number = c.getInt("number");
if(position!=null){
//TODO You know it is position and it's int value
}else if(number!=null){
//TODO You know it is number and it's int value
}else{
//TODO Its neither of two
}
If you're using Gson to convert your JSON to a class, you can use both position and number as attributes for your destination class.
After that, check which one is null and which one is not and use that is not null as your number.
Just try this one,
JSONObject object = (Your jsonObject);
if(object.has("position")){
** do your code here **
}else if(object.has("number"){
** do your code here **
}
my collection contains documents like this:
{
"_id": ObjectId("585a7886e4b06aec5d1d1639"),
"name": "somename",
"owner": "someowner",
"slots": 50,
"gold": 0,
"tag": "sometext",
"motd": "sometext",
"purchases": [],
"members": {
"membername1": {
"rank": 2
},
"membername2": {
"rank": 5
},
"membername3": {
"rank": 3
}
}
}
I need to get int value from "members.membername.rank".
how do I get this value, knowing only membername?
The following code excludes the document's ID and gets only the rank for memername1
List<Document> pipeline = Arrays.asList(new Document("$project", new Document("rank", "$members.membername1.rank").append("_id", false)));
return ApiResponse.withBody(coll.aggregate(pipeline).first().getInteger("rank"));
This is my response data:
"response": {
"numFound": 2,
"start": 0,
"docs": [
{
"total_amount": 10,
"id": "2"
},
{
"total_amount": 10,
"id": "1"
}
]
}
I want to get sum of total_amount. I tried facet query also. But I did't get sum. I got some blog on this but that is for solr 5.1. http://yonik.com/solr-facet-functions/
You can use the stats functionality to get this information. Just put the followed parameters in your query:
stats=true&stats.field=total_amount
Your response will be like that:
"response": {
"numFound": 2,
"start": 0,
"docs": [
{
"id": "1",
"total_amount": 15
},
{
"id": "2",
"total_amount": 12
}
]
},
"stats": {
"stats_fields": {
"total_amount": {
"min": 12,
"max": 15,
"count": 2,
"missing": 0,
"sum": 27,
"sumOfSquares": 369,
"mean": 13.5,
"stddev": 2.1213203435596424,
"facets": {}
}
}
Note that you have lots of information around the total_amount field including the sum.