how to create linked hash map object for this json - java

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

Related

How to remove an attribute from RequestSpecification/FilterableRequestSpecification body?

Dears,
I am working on creating a simple method which will take String argument which will be a path or other kind "pointer" to attribute/s in JSON and this method will remove those attribute/s.
My problem is I can find values of those attribute/s using JsonPath, but I can't find methods in rest assured (or other libraries) which could remove/delete attributes by given path.
JSON is already added earlier so i need to pull him from RequestSpecification or FilterableRequestSpecification object ex.
RequestSpecification rs = *objFromContext*;
FilterableRequestSpecification frs= (FilterableRequestSpecification) rs;
frs.getBody();
I've tried to work with JSONObject class and remove() but it doesn't work on complex JSONs.
given example JSON
{
"created": "string",
"updated": "string",
"items": [
{
"code": "TEST",
"nested": {
"code": "test",
"name": "name",
"other": [
{
"code": "TEST",
"name": "myName",
"quantity": 1
}
]
},
"itemsProperties": [
{
"code": "value1",
"name": "name",
"value": 123
}
]
},
{
"code": "TEST",
"nested": {
"code": "test",
"name": "name",
"other": [
{
"code": "TEST",
"name": "myName",
"quantity": 1
}
]
},
"itemsProperties": [
{
"code": "value2",
"name": "name",
"value": 123
}
]
}
],
"timer": {
"startDate": "2015-01-01",
"endDate": "2021-01-02"
},
"id": "myId"
}
using JsonPath jp = JsonPath.from(httpRequest.getBody().toString());
and then jp.get(items.itemsproperties.code) i can find value1 and value2.
I stuck in this point: How to remove those attributes from sended body?
I know i can convert body into JSONObject and then go field after field conversion between getJSONArray and GetJSONOBject and remove those fields, but i would like to make this metod much more universal.
Is this possible?
If you want to manipulate json in Rest-Assured JsonPath, then the answer is No. You can't do that. JsonPath help you to extract value from json, that's it, no more.
You have to use different libraries to remove key-value pair.
For example: using JsonPath Jayway
DocumentContext parse = JsonPath.parse(body);
parse.delete("$..itemsProperties..code");
System.out.println(parse.jsonString());

I need to send the request correctly, but I don't know how to get the required values from objects

How to get a new list from the list of objects?
I need a new list of objects to POST request
this list of objects i get from response:
{
"success": true,
"body": {
"users": [
{
"type": "unknown",
"data": [
{
"id": "8",
"firstName": "Jackson",
"lastName": "Baker",
"group": "false"
},
{
"id": "11",
"firstName": "Charlotte",
"lastName": "Garcia",
"group": "false"
},
{
"id": "7",
"firstName": "Henry",
"lastName": "Thompson",
"group": "false"
},
{
"id": "24",
"firstName": "Elijah",
"lastName": "Miller",
"group": "false"
}
]
}
]
}
}
I need to form a new object from response:
{
"success": true,
"body": {
"users": [
{
"type": "unknown",
"data": [
{
"id": "8",
"group": "false"
},
{
"id": "11",
"group": "false"
},
{
"id": "7",
"group": "false"
},
{
"id": "24",
"group": "false"
}
]
}
]
}
}
This new list of object I need to post a request.
I have a JSON Schema, but i don't know how i can make this structure.
My problem is that I can't get the values from fields. I'm using the path "body.users.data.find {it.id} .id" but it finds the id array but I need a users list with values from two fields.
As the users node and data node are all list type, you need use two loop:
import groovy.json.JsonSlurper
// text is your json response text
def result = new JsonSlurper().parseText(text)
result.body.users.each{it.data.each{it.remove("firstName");it.remove("lastName")}}
// result is the what you wanted
println(result)

Rest-assured. get value from another value

I have a json response something like this:
"results": [
{
"id": "1",
"name": "YYY",
"shortName": "Y"
},
{
"id": "2",
"name": "XXX",
"shortName": "X"
},
{
"id": "3",
"name": "ZZZ",
"shortName": "Z"
}
]
I want to get id value when I send name value. For example if name = ZZZ return me id value in this case 3 using rest assured
Json path json-path-2.9.0 with rest-assured
import static com.jayway.restassured.path.json.JsonPath.from;
below JsonPath query
from(response).getList("results.findAll { it.name=='ZZZ' }.id").toString() //returns 3
from(response).getList("results.findAll { it.name=='XXX' }.id").toString() //returns 2

Sort the JSON Body of HTTP Request alphabetically [duplicate]

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.

Exclude properties from Json data without deserializing it

I have Json data like this:
{
"_id": "123",
"transaction": {
"className": "ExpenseReport",
"id": "789",
"createdBy": {
"firstName": "Donald",
"lastName": "Morgan",
"address": {
"street1": "1362 Woodlawn Lane",
"street2": "Suite #100805",
"place": {
"city": "Darien",
"state": "CA",
"country": "USA",
"number": "OBJ-4823478",
"createdBy": "Brett Wright"
},
"zip": 88884,
"number": "OBJ-5740231",
"createdBy": "Brett Wright"
},
"number": "OBJ-3561551",
"createdBy": "Brett Wright"
},
"score": 12,
"reasonCodes": [
"these",
"are",
"strings"
]
}
}
I want a subset of this data after excluding some properties, say something like this:
{
"_id": "123",
"transactionType": "EXPENSE_REPORT",
"transaction": {
"className": "ExpenseReport",
"id": "789",
"createdBy": {
"firstName": "Donald",
"lastName": "Morgan",
"address": {
"street1": "1362 Woodlawn Lane",
"street2": "Suite #100805",
"place": {
"city": "Darien",
"state": "CA",
"country": "USA"
},
"createdBy": "Brett Wright"
},
"createdBy": "Brett Wright"
},
"score": 12
}
}
Now one way would be to deserialize the original json data into a POJO, use Jackson Views to annotate the required properties, and then serialize the same POJO again to get the Json data without the properties.
But I want to achieve something like this WITHOUT DESERIALIZING the Json data, say by just parsing the json data and removing the key-value pairs if they are not found in a collection. Is anyone aware of any library that does that?
Jackson allows you to do only the parsing step using ObjectMapper.readTree()
JsonNode root = om.readTree(input);
The resulting JsonNodes are mutable, so something like this does the job:
ObjectNode place = (ObjectNode)(root.findPath("transaction")
.findPath("createdBy")
.findPath("address")
.findPath("place")
);
place.remove("number");
This is --unfortunately-- not too nice, but can be easily wrapped into a generic method that takes a property path:
void deleteProperty(JsonNode root, List<String> propPath)
{
JsonNode node = root;
for (String propName: propPath.subList(0, propPath.size() - 1)) {
node = node.findPath(propName);
}
// completely ignore missing properties
if ((! node.isMissingNode()) && (! node.isEmpty())) {
if (node instanceof ObjectNode) {
final ObjectNode parent = (ObjectNode)node;
parent.remove(propPath.get(propPath.size() - 1));
}
}
}
It is then possible to write out the modified node tree using writeTree().
There is also the property filter API. Unfortunately while it is easy to filter out individual properties with it, it is non-trivial to use it for property paths. For example, in your case, the trivial filter can only filter out all createdBy properties.

Categories

Resources