Create new json file using json template file - java

I have a json template file. Using java program, I need to read the template and create a new json file with updated values.
Example Template json example:
{
"page": 2,
"per_page": 6,
"total": 12,
"total_pages": 2,
"data": [
{
"id": 7,
"email": "michael.lawson#reqres.in",
"first_name": "Michael",
"last_name": "Lawson",
"avatar": "https://reqres.in/img/faces/7-image.jpg"
}
],
"support": {
"url": "https://reqres.in/#support-heading",
"text": "To keep ReqRes free, contributions towards server costs are appreciated!"
}
}
Expected output json file: (updated page,first name, last name, email, text)
{
"page": 3,
"per_page": 6,
"total": 12,
"total_pages": 2,
"data": [
{
"id": 7,
"email": "updated#email.com",
"first_name": "MichaelPatric",
"last_name": "lastName",
"avatar": "https://reqres.in/img/faces/7-image.jpg"
}
],
"support": {
"url": "https://reqres.in/#support-heading",
"text": "text udpated"
}
}
Need a generic java code/logic using which we can modify any values from template json and create new output json file.
Thanks in advance!

Related

How to get a child object in response with java streams

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.

Implementing a JSON Object in java

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.

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.

How to get rid of "col1" aliases from aggregate struct objects in Spark?

I'm trying to aggregate json objects to json list - dynamically create struct objects that are created with various amount of fields. Each time I create an aggregate using the below snippet:
batched = dataset.select(col(asteriskChar), row_number()
.over(Window.orderBy(order)).alias(rowNumAlias))
.withColumn(batchAlias, functions.ceil(col(rowNumAlias).divide(batchSize)))
.groupBy(col(batchAlias)) .agg(functions.collect_list(struct(structCol)).alias(batchedColAlias));
I would like to have object batches like below:
[
{
"id": 1,
"first": "John",
"last": "Thomas",
"score": 88
},
{
"id": 2,
"first": "Anne",
"last": "Jacobs",
"score": 32
}
]
, but I got below:
[
{
"col1": {
"id": 1,
"first": "John",
"last": "Thomas",
"score": 88
}
},
{
"col1": {
"id": 2,
"first": "Anne",
"last": "Jacobs",
"score": 32
}
}
]
How can I get rid of "col1" fields and make those jsons a single objects within an array? Thank you in advance.
Most probably you don't need the struct there:
.groupBy(col(batchAlias))
.agg(functions.collect_list(structCol).alias(batchedColAlias));

How to convert the tree structured json to Java object using gson

[
{
"sentence": "I want to buy shoes .",
"tree": {
"ROOT": [
{
"index": 2,
"token": "want",
"label": "VERB",
"pos": "VBP",
"tree": {
"nsubj": [
{
"index": 1,
"token": "I",
"label": "PRON",
"pos": "PRP"
}
],
"xcomp": [
{
"index": 4,
"token": "buy",
"label": "VERB",
"pos": "VB",
"tree": {
"aux": [
{
"index": 3,
"token": "to",
"label": "PRT",
"pos": "TO"
}
],
"dobj": [
{
"index": 5,
"token": "shoes",
"label": "NOUN",
"pos": "NNS"
}
]
}
}
],
"punct": [
{
"index": 6,
"token": ".",
"label": ".",
"pos": "."
}
]
}
}
]
}
}
]
This is tree represented in Json. But the keys for nested nodes keep changing.
For example "ROOT, nsubj, xcomp" ... etc.
How do I convert above json code to Java Object using gson.
Above response is from syntaxnet Parsey_Mcparseface api I'm trying to use.
Thanks in advance.
Gson has a method Gson#fromJson. For example, this is a code to read a simple String object.
Gson gson = new Gson();
String str = gson.fromJson("\"hello\"", String.class);
System.out.println("String: " + str);
You need to prepare Java Object to read your proposed JSON. But, you don't need to write code by yourself. There is a website providing automatical JSON object generator.
jsonschema2pojo
enter following items:
Target language: Java
Source type: JSON
Annotation type: Gson
and enter your class name, for example "ParsedSentence"
then, write code. You will get object.
Gson gson = new Gson();
ParsedSentence parsed = gson.fromJson(longLongJsonString, ParsedSentence.class);

Categories

Resources