Sort the JSON Body of HTTP Request alphabetically [duplicate] - java

This question already has answers here:
How to create json, sorted on keys, using gson?
(3 answers)
Closed 2 years ago.
I am doing an API call with certain parameters. The body of the Request is something like this:
{
"billing": {
"firstname": "John",
"lastname": "Master",
"email": "abc.com"
},
"address": {
"firstname": "John",
"lastname": "Master",
"email": "abc.com",
"telephone": "+919999999999"
},
"payments": [
{
"code": "abcd",
"amount": 500
}
],
"refno": "abcd123",
"successUrl": "https://baseurl/ordercomplete/success",
"failureUrl": "https://baseurl/ordercomplete/failure",
"products": [
{
"sku": "sampleSKU",
"price": 500,
"qty": 1,
"currency": 356,
"giftMessage": "",
"theme": ""
}
],
"syncOnly": true,
"deliveryMode": "API"
}
I want to sort the parameters of the request alphabetically. The sorting should be done at outer level and inner level as well. For example, address should come before billing after the sort. Within the internal JSON also I want it to be sorted. For example in the billing struct email should come before lastname.
So the answer that I am looking for is:
{
"address": {
"firstname": "John",
"lastname": "Master",
"email": "abc.com",
"telephone": "+919999999999"
},
"billing": {
"firstname": "John",
"lastname": "Master",
"email": "abc.com"
},
"deliveryMode": "API",
"failureUrl": "https://baseurl/ordercomplete/failure",
"payments": [
{
"code": "abcd",
"amount": 500
}
],
"products": [
{
"sku": "sampleSKU",
"price": 500,
"qty": 1,
"currency": 356,
"giftMessage": "",
"theme": ""
}
],
"refno": "abcd123",
"successUrl": "https://baseurl/ordercomplete/success",
"syncOnly": true
}
I think I can do this by creating multiple POJO class having all the field and then implement a comparator which will sort it alphabetically. But this way of doing will make it very difficult even if a single field in the parameter of the request body change.
So I was thinking can we do it some better way where we do not have to worry about the field structure.

You could use Jackson ObjectMapper and configure ObjectMapper as
om.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
Hope it was useful.

Related

Filter nested json data using jsonpath as in example

I am using jsonpath to filter.
Json(Dummy json just to explain) source String, which is basically a list of Operating systems and details of its programs etc. In this example, the OS whose id = 1403 is a windows 10 OS and has 2 features acchritecture and browser. There are more details to the browser feature as shown in json
[
{
"id": 1403,
"os": "window 10",
"features": [
{
"id": 1356,
"name": "architecture",
"value": [
{
"id": 1308,
"feature": [
{
"id": 1262,
"key": "name",
"value": "amd64"
}
]
}
],
"category": "cat1"
},
{
"id": 1357,
"name": "browser",
"value": [
{
"id": 1309,
"feature": [
{
"id": 1263,
"key": "name",
"value": "Firefox"
},
{
"id": 1265,
"key": "version",
"value": "187"
}
]
}
],
"category": "cat2"
}
]
},
{
"id": 2804,
"os": "window 7",
"features": [
{
"id": 2764,
"name": "architecture",
"value": [
{
"id": 2719,
"feature": [
{
"id": 2679,
"key": "name",
"value": "amd64"
}
]
}
],
"category": "cat1"
},
{
"id": 2765,
"name": "browser",
"value": [
{
"id": 2722,
"feature": [
{
"id": 2685,
"key": "name",
"value": "Chrome"
},
{
"id": 2684,
"key": "version",
"value": "87.0.4280.88"
}
]
}
],
"category": "cat2"
}
]
}
]
I want to be able to filter the json such that
features[*].name == 'browser' and features[*].value[*].feature[*].value == 'chrome'
What will be the JsonPath string that can help me achieve above query? The above query uses similar syntax used by JsonPath string but doesn't do the job. Its just to explain.
There is another example here gets Movie Title Given 'Starring' field
And would like to get the full OS json that fulfils this condition. In this case a array of OS which contains only one OS i.e. with id= 2804
[
{
"id": "2804",
...
}
]
I am stuck much before what aim to achieve. Here is my code to get all the OS that have "name=browser". I get the array but it only contains value[] items. I want it get the full json. It returns object with IDs- 1357, 2765.
List<Map<String, Object>> expensive = JsonPath.parse(jsonDataSourceString)
.read("$[*].features[*].[?(#.name == 'browser')]");
To get the outer array you need to use the filter like $[?(...)]
For your current use case, we need to use nested array filters. There is an open issue in JsonPath for filter on children level. (Refer here).
Luckily, there is a workaround suggested to use contains over here.
we can use the below expression to filter:
List<Object> expensive = JsonPath.parse(jsonDataSourceString)
.read("$[?(#.features[?(#.name == 'browser')].value[*].feature[*].value contains 'Chrome')]");
Prints the below output
{id=2804, os=window 7, features=[{"id":2764,"name":"architecture","value":[{"id":2719,"feature":[{"id":2679,"key":"name","value":"amd64"}]}],"category":"cat1"},{"id":2765,"name":"browser","value":[{"id":2722,"feature":[{"id":2685,"key":"name","value":"Chrome"},{"id":2684,"key":"version","value":"87.0.4280.88"}]}],"category":"cat2"}]}

How do i limit the number of array elements retrieved by a GET request (REST API JAVA)

Supposedly, My API retrieves JSON having around 100 ids and its respective values.
How do i limit it to first 10 ids with its values?
Is there any JAVA code to limit this?
[
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere#april.biz",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
},
{
"id": 2,
"name": "Ervin Howell",
"username": "Antonette",
"email": "Shanna#melissa.tv",
"address": {
"street": "Victor Plains",
"suite": "Suite 879",
"city": "Wisokyburgh",
"zipcode": "90566-7771",
"geo": {
"lat": "-43.9509",
"lng": "-34.4618"
}
},
"phone": "010-692-6593 x09125",
"website": "anastasia.net",
"company": {
"name": "Deckow-Crist",
"catchPhrase": "Proactive didactic contingency",
"bs": "synergize scalable supply-chains"
}
},
..... "id":100, ...
Pagination is your best bet for this. So you could pass in some query params to the API call like limit and pageNumber. For example, GET /users?limit=10&page=1 will get you the first 10. If you are using Spring and a database on the backend. Spring Data JPA has pagination built in and it's fairly easy to use.
You can use pagination to apply for the limit and page number.
You can make a fetch request like => fetch(${url}/_limit=10&_page=1)
and this will fetch you your desired output

how to create linked hash map object for this json

I am trying to call an API using Retrofit in android. For this API I need the input parameter JSON object in proper sequence.
Only if I have the json in required sequence I get successful response from the API, otherwise it gives an error. To handle this issue I got one solution that is to first create a LinkedHashMap of input parameter then create the JSON of that LinkedHashMap. This way I'm acheaving the response from api.
but right now im confused how to create linkedHash map for below json
{
"RequestXml": {
"Authenticate": {
"InterfaceCode": "1",
"InterfaceAuthKey": "AirticketOnlineWebSite",
"AgentCode": "MOS0000001",
"Password": "KGBW5P"
},
"BookTicketRequest": {
"TrackNo": "0$182967|4|1AO",
"MobileNo": "9099776464",
"AltMobileNo": "9898989898",
"Email": "abc#gmail.com",
"Address": "Test",
"ClientRequestID": "",
"Passengers": {
"Passenger": [
{
"PaxSeqNo": "1",
"Title": "Mr",
"FirstName": "Savan",
"LastName": "Test",
"PassengerType": "A",
"DateOfBirth": "01/12/1992",
"PassportNo": "RTTTTGGBGB56356",
"PassportExpDate": "01/12/2024",
"PassportIssuingCountry": "IND",
"NationalityCountry": "IND"
}
]
},
"Segments": {
"Segment": [
{
"TrackNo":"0$182967|4|1AO",
"SegmentSeqNo": "1",
"AirlineCode": "UK",
"FlightNo": "888",
"FromAirportCode": "BOM",
"ToAirportCode": "DEL",
"DepDate": "30/09/2019",
"DepTime": "14:00",
"ArrDate": "30/09/2019",
"ArrTime": "16:00",
"FlightClass": "E",
"MainClass": "Y"
}
]
},
"AdditionalServices": {
},
"TotalAmount": "4735",
"MerchantCode": "PAY9zJhspxq7m",
"MerchantKey": "eSpbcYMkPoZYFPcE8FnZ",
"SaltKey": "WHJIIcNjVXaZj03TnDme",
"IsTicketing": "Yes"
}
}
}

How to parse JSON nested arrays [duplicate]

This question already has answers here:
How do I parse JSON in Android? [duplicate]
(3 answers)
Closed 5 years ago.
"sport_events": [
{
"id": "sr:match:12606716",
"scheduled": "2017-09-27T10:00:00+00:00",
"start_time_tbd": false,
"status": "closed",
"tournament_round": {
"type": "group",
"number": 1,
"group": "Gr. 4"
},
"season": {
"id": "sr:season:45960",
"name": "U17 European Ch.ship QF 17/18",
"start_date": "2017-09-27",
"end_date": "2018-04-30",
"year": "17/18",
"tournament_id": "sr:tournament:755"
},
"tournament": {
"id": "sr:tournament:755",
"name": "U17 European Ch.ship QF",
"sport": {
"id": "sr:sport:1",
"name": "Soccer"
},
"category": {
"id": "sr:category:392",
"name": "International Youth"
}
},
"competitors": [
{
"id": "sr:competitor:22646",
"name": "Russia",
"country": "Russia",
"country_code": "RUS",
"abbreviation": "RUS",
"qualifier": "home"
},
{
"id": "sr:competitor:22601",
"name": "Faroe Islands",
"country": "Faroe Islands",
"country_code": "FRO",
"abbreviation": "FRO",
"qualifier": "away"
}
]
},
Add gson to your project by adding this into your build-script.gradle:
dependencies {
compile 'com.google.code.gson:gson:2.8.2'
}
Now create the classes you need but first correct your json string. I guess you forgot a attributename at the beginning. This is your new best friend: json formatter online
After you corrected your json-string and you´ve created your Wrapper and Pojo model-classes with the needed attributes, you parse the string back into the wrapper-object and with getter/setter you get change/get data out of it.
Gson gson = new GsonBuilder().create();
Wrapper wrap = gson.fromJson(jsonString, Wrapper.class);
Don´t forget try-catch block because there can be many thrown exceptions.
Good luck to you.
How-to-for-beginner

tExtractJSONField From tFileInputJSON - Talent Open Studio

I am very new to Talend Open Studio for DI. I am trying to read data from the below JSON File :
{
"data": [
{
"id": "X999_Y999",
"from": {
"name": "Tom Brady", "id": "X12"
},
"message": "Looking forward to 2010!",
"actions": [
{
"name": "Comment",
"link": "http://www.facebook.com/X999/posts/Y999"
},
{
"name": "Like",
"link": "http://www.facebook.com/X999/posts/Y999"
}
],
"type": "status",
"created_time": "2010-08-02T21:27:44+0000",
"updated_time": "2010-08-02T21:27:44+0000"
},
{
"id": "X998_Y998",
"from": {
"name": "Peyton Manning", "id": "X18"
},
"message": "Where's my contract?",
"actions": [
{
"name": "Comment",
"link": "http://www.facebook.com/X998/posts/Y998"
},
{
"name": "Like",
"link": "http://www.facebook.com/X998/posts/Y998"
}
],
"type": "status",
"created_time": "2010-08-02T21:27:44+0000",
"updated_time": "2010-08-02T21:27:44+0000"
}
]
}
I want to load three attributes into my table ( id, actions_name and actions_link). So, in the first step (tFileInputJSON) - I tried to do a Loop Json query as below:
Here, am able to extract the rows as I needed. But, then I used a tExtractJSONField to extract individual fields under "actions" for each "id" using XPath expressions as below:
I tried several other ways to extract the fields but could not do this. Also, not able to find any correct post in stack overflow and talent forums very relevant to my question. Could somebody please help?
Arrange the job like ,
tFileInputJSON is like,
tExtractJSONFields is like,
Then you will get output as,

Categories

Resources