How to get a child object in response with java streams - java

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.

Related

JSON Object Navigation to nested value

I am new to JSON and trying to manipulate JSON for some validation
My JSON looks like this . I need to pick the JSON object based on the refcode and then get count of different object in that, and navigate deeper inside to get the key value pair. Can someone guide me how I can navigate.
{
"components": [
{
"id": 12,
"text": "ABC",
"refCode": "CO_ABC",
"patternCode": "0",
"components": [
{
"id": 1234,
"text": "types",
"refCode": "CO_TYPES",
"questions": [
{
"questionId": 122324,
"questionText": "Is this you",
"questionSequence": 1,
"questionRefCode": "QN_STAY",
"hasPreselectedAnswer": false,
"responsesMetadata": {
"cardinality": "single",
"patternCode": "5",
"dataType": "STRING",
"numberMin": null,
"numberMax": null
},
"choices": [
{
"choiceId": 5456,
"choiceRefCode": "YES",
"choiceText": "Yes",
"sequence": 1
},
{
"choiceId": 8798,
"choiceRefCode": "NO",
"choiceText": "No",
"sequence": 2
}
],
"editable": true,
"accessible": true
}
]
},
{
"id": 13,
"text": "State of stay",
"refCode": "CO_STATE",
"questions": [
{
"questionId": 1,
"questionText": "Which state do you stay",
"questionSequence": 2,
"questionRefCode": "QN_STATE",
"hasPreselectedAnswer": false,
"responsesMetadata": {
"cardinality": "multiple",
"patternCode": "1",
"dataType": "STRING",
"numberMin": null,
"numberMax": null
},
"choices": [
{
"choiceId": 1,
"choiceRefCode": "CH_AZ",
"choiceText": "Arizona",
"sequence": 1
},
{
"choiceId": 2,
"choiceRefCode": "CH_PA",
"choiceText": "Pennsylvania",
"sequence": 2
}
],
"accessible": true
}
]
}
]
}
]
}

getting array of ids , but need to get String

I,m testing API with rest assured , and trying to get Id's from my created product as a String with the following method below
String productId = response.jsonPath().getString("productPrices.productId");
String channelId = response.jsonPath().getString("productPrices.channelId");
but it's returning me an array
when I print out those Ids, the following output is being got;
System.out.println("productId is ===> " +productId);
System.out.println("channelId is ===> " +channelId);
Output is
productId is ===>[jpjeneOM]
channelId is ===>[5bpJKaVE]
My issue is , i need to get those Ids as a String only !!!
pls help me to resolve this issue
thanks in advance
And I have the following payload
{
"id": "jpjeneOM",
"name": "NewProductForTest",
"productTypeId": null,
"active": true,
"shortDescription": "API",
"fullDescription": "API Automation",
"policy": null,
"mostPopular": null,
"longitude": 34.774667,
"latitude": 32.085814,
"calendarColor": "blue",
"address": "Dizengoff Street, Tel Aviv-Yafo",
"cityId": "nlYxZ6az",
"createdAt": "2021-08-06T07:49:14.920615",
"productImages": [
],
"productDocuments": [
],
"productTypes": null,
"productWorkingDates": [
{
"id": "baQkKROA",
"productId": "jpjeneOM",
"fromDate": "2021-05-27",
"toDate": "2022-12-31",
"name": "StrickHours",
"strictHours": true,
"timeSlots": [
{
"id": "1lkvdZa6",
"productWorkingDateId": "baQkKROA",
"dayOfWeek": "Monday",
"startTime": "09:00:00",
"endTime": "20:00:00",
"duration": "01:00:00",
"quantity": 67,
"usedQuantity": 0,
"active": true,
"deletedAt": null
}
],
"deletedAt": null,
"maxUsedTicketsQuantity": 0,
"errorCode": 0
}
],
"productRegions": [
{
"id": "4lrWZgOd",
"productId": "jpjeneOM",
"regionId": "5bpJKaVE",
"regionName": null
}
],
"productPrices": [
{
"id": "1lon0Aa7",
"productId": "jpjeneOM",
"channelId": "5bpJKaVE",
"fromDate": "2021-08-02T00:00:00",
"toDate": "2022-12-31T00:00:00",
"title": "API",
"remarks": "Test",
"officialPrice": 34,
"currencyId": "5bpJKaVE",
"quantityPerDay": 123,
"autoConfirm": true,
"pricePerPerson": false,
"productPriceTypes": [
{
"id": "xl4WJ7aj",
"productPriceId": "1lon0Aa7",
"productCustomerTypeId": "ZOw36ZOx",
"amount": 12,
"currencyId": "5bpJKaVE",
"currencySymbol": null,
"isOfficial": false,
"productCustomerType": null
}
],
"deletedAt": null
}
]
The productPrices in example is an array, and you didn't mention which one to choose, the jsonpath syntax is like productPrices.*.channelId, so you get arrays. You can choose the first one like productPrices.0.channelId or else.

How to write a REST API method for which consume json format for list of objects

I have written a method as following.
#POST
#Path("/add")
#Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
#Consumes(MediaType.APPLICATION_JSON + ";charset=utf-8")
public boolean createMeasurement(List<MeasurementBean> list ,#HeaderParam(AUTHORIZATION) String authString){
Gson gson = new Gson();
LoginSession loginSession=null;
try{
loginSession = LoginUtility.validateKey(authString);
ResultRO<List<HashMap<String, Object>>> resultRO = loginSession
.execute(new Callable<ResultRO<List<HashMap<String, Object>>>>() {
#Override
public ResultRO<List<HashMap<String, Object>>> call() throws Exception {
String key[] = idKey.split(":");
String type = key[0];
long testId = Long.parseLong("2");
return doGetCreateMeasurement(list ,2);
}
});
return gson.toJson(true);
}catch(Exception ex){
ex.printStackTrace();
}
return null;
}
I am not able to consume the list of objects from json format.
and my json is in following format
{
"beans": [{
"id": 1133,
"testConditionGroupId": 0,
"testId": 0,
"type": 0,
"completeFlag": 0,
"invalidFlag": 0,
"retentionFlag": 0,
"delBeforeFlag": 0,
"dontReplicateFlag": 0,
"releaseFlag": 0,
"timeBase": 0.0,
"name": "MeaResult_TEST_XYZABCD",
"version": "V.1.0.1",
"description": "M_Test",
"mimeType": "MIME",
"stardDate": "",
"endDate": "",
"attributeList": [{
"id": 0,
"name": "Test_Attribute1",
"value": "A",
"unit": "ms"
}, {
"id": 0,
"name": "Test_Attribute2",
"value": "B",
"unit": "ms"
}],
"subMatrixList": [{
"id": 0,
"name": "Test_SubMatrixBean1_New",
"version": "V.1.0.0",
"mimeType": "MimeTyep",
"NumberOfvalues": 3,
"noOfRows": 1,
"localColumnList": [{
"id": 0,
"name": "TestName_1_New",
"version": "V.1.0.0",
"mimeType": "MimeTyep",
"sequence_Representation": "explicit",
"independent": 1,
"global_Flag": 15,
"raw_Datatype": 1,
"dataValues": ["1", "2", "3"],
"flags": [15, 15, 15],
"generation_Parameters": [1.0, 2.0, 3.0],
"externalComponents": [],
"attributeList": [],
"meaQuantity": {
"id": 0,
"name": "TestName_1_New",
"unit": "ms",
"quantityName": "MeaQuantity_Quantity",
"description": "MeaQuantity_Test",
"localName": "TestName_1_New",
"size": 10,
"dataType": 1,
"min": 1.0,
"max": 10.0,
"attributeList": [{
"id": 0,
"name": "Test_Attribute1",
"value": "A",
"unit": "ms"
}, {
"id": 0,
"name": "Test_Attribute2",
"value": "B",
"unit": "ms"
}]
}
}],
"attributeList": [{
"id": 0,
"name": "Test_Attribute1",
"value": "A",
"unit": "ms"
}, {
"id": 0,
"name": "Test_Attribute2",
"value": "B",
"unit": "ms"
}]
}],
"meaQuantityList": [{
"id": 0,
"name": "TestName_1_New",
"unit": "ms",
"quantityName": "MeaQuantity_Quantity",
"description": "MeaQuantity_Test",
"localName": "TestName_1_New",
"size": 10,
"dataType": 1,
"min": 1.0,
"max": 10.0,
"attributeList": [{
"id": 0,
"name": "Test_Attribute1",
"value": "A",
"unit": "ms"
}, {
"id": 0,
"name": "Test_Attribute2",
"value": "B",
"unit": "ms"
}]
}]
}]
}
but when I am trying to POST request using postman it gives following error
WARNING: No message body reader has been found for request class MeasurementBeans, ContentType : application/json.
and also method is not executing.
You are accepting a List<MeasurementBean> in the createMeasurement() method and the JSON you have mentioned is an object.
{
"beans": []
//..
}
Just make it as an array by removing the starting {, "beans:" and ending }, i.e you just need to pass the array.

JSON Object changes randomly from api

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 **
}

How do I get sum of a field in solr 4.8

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.

Categories

Resources