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.
Related
I have two JSON strings which are essentially arrays of JSONObject. The two JSON strings have below structure and keys:
JSON-1:
[
{
"title": "ABC",
"edition": 7,
"year": 2011
},
{
"title": "DEF",
"edition": 2,
"year": 2012
},
{
"title": "XYZ",
"edition": 3,
"year": 2013
}
]
And, JSON-2:
[
{
"title": "ABC",
"price": "20"
},
{
"title": "DEF",
"price": "20"
},
{
"title": "XYZ",
"price": "20"
}
]
Both these JSONs have a common key "title" based on which I want to merge these two JSONs, either merging JSON-2 values into JSON-1 or creating a JSON object with the merged result.
The merged result should look like below:
[
{
"title": "ABC",
"edition": 7,
"year": 2011,
"price": "20"
},
{
"title": "DEF",
"edition": 2,
"year": 2012
"price": "20"
},
{
"title": "XYZ",
"edition": 3,
"year": 2013
"price": "20"
}
]
How can I achieve this by minimum looping and minimum object creation? I also can not use entity/model classes. The idea is to do it without creating any model classes.
Note: I cannot use Gson because I don't have the approval to use the same.
I tried to use List<JSONObject> listObj = objectMapper.readValue(jsonOneString, new TypeReference<List<JSONObject>>(){});,
but I am getting an unknown property exception.
I tried JsonNode node = objectMapper.readTree(jsonOneString);, but I cannot proceed much further with this approach.
I know what I am doing here is highly inefficient, so looking for ways which will use no entity class, minimum new object creation and minimum loops. Kindly advise.
UPDATE: I updated the below code with a slight modification:
if (json1elem.get("title")!=null
&& json2elem.get("title")!=null
&& json1elem.get("title").equals(json2elem.get("title"))) {
//
}
JsonNode json1 = objectMapper.readTree(jsonOneString);
JsonNode json2 = objectMapper.readTree(jsonTwoString);
for (JsonNode json1elem : json1) {
for (JsonNode json2elem : json2) {
if (json1elem.get("title").equals(json2elem.get("title"))) {
((ObjectNode) json1elem).setAll((ObjectNode) json2elem);
break;
}
}
}
System.out.println(json1.toPrettyString());
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!
This is the JSON Response I received from OpenWeatherMap:
{
"coord": {
"lon": 85.84,
"lat": 20.26
},
"weather": [
{
"id": 721,
"main": "Haze",
"description": "haze",
"icon": "50d"
}
],
"base": "stations",
"main": {
"temp": 305.15,
"pressure": 1007,
"humidity": 70,
"temp_min": 305.15,
"temp_max": 305.15
},
"visibility": 5000,
"wind": {
"speed": 4.1,
"deg": 170
},
"clouds": {
"all": 20
},
"dt": 1551686400,
"sys": {
"type": 1,
"id": 9113,
"message": 0.0037,
"country": "IN",
"sunrise": 1551659668,
"sunset": 1551702153
},
"id": 1275817,
"name": "Bhubaneswar",
"cod": 200
}
While I am able to use Weather by using this code below but unable to convert main to array. Is there anyway I can convert the bolded response to array or String.
JSONObject jsonObject = new JSONObject(result);
String weatherInfo = jsonObject.getString("weather");
JSONArray arr = new JSONArray(weatherInfo);
for(int i=0;i<arr.length();i++)
{
JSONObject jsonPart = arr.getJSONObject(i);
String main = jsonPart.getString("main");
String description =jsonPart.getString("description");
if(main !="" && description !="")
{
message += main + " : " + description + "\r\n";
}
}
The suggestion is, don't parse the JSON by hand. Use third party library like Gson to parse the JSON. This way you won't run into any typo errors and let the library handle the parsing for you.
Paste your json string to this website, and generate your pojo. Use the Gson to parse your string and bind to generated pojo.
[
{
"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);
Im requesting data from instagram api when I search for any tag. In return I get a massive chunk of json data corresponding to like 20 pictures. The response below is the chunk I used to generate my pojos online
{
"pagination": {
"next_max_tag_id": "1193052000552992097",
"deprecation_warning": "next_max_id and min_id are deprecated for this endpoint; use min_tag_id and max_tag_id instead",
"next_max_id": "1193052000552992097",
"next_min_id": "1193052554319844057",
"min_tag_id": "1193052554319844057",
"next_url": "https://api.instagram.com/v1/tags/cats/media/recent?access_token=631477962.1fb234f.f7c5cda97c7f4df983b1c764f066ed37&max_tag_id=1193052000552992097"
},
"meta": {
"code": 200
},
"data": [
{
"attribution": null,
"tags": [
"cats",
"caseworker",
"homestuck"
],
"type": "image",
"location": null,
"comments": {
"count": 0,
"data": []
},
"filter": "Normal",
"created_time": "1456442969",
"link": "https://www.instagram.com/p/BCOkvoim1LZ/",
"likes": {
"count": 0,
"data": []
},
"images": {
"low_resolution": {
"url": "https://scontent.cdninstagram.com/t51.2885-15/s320x320/e35/12729405_224148847934280_1450226662_n.jpg?ig_cache_key=MTE5MzA1MjU1NDMxOTg0NDA1Nw%3D%3D.2",
"width": 320,
"height": 320
},
"thumbnail": {
"url": "https://scontent.cdninstagram.com/t51.2885-15/s150x150/e35/12729405_224148847934280_1450226662_n.jpg?ig_cache_key=MTE5MzA1MjU1NDMxOTg0NDA1Nw%3D%3D.2",
"width": 150,
"height": 150
},
"standard_resolution": {
"url": "https://scontent.cdninstagram.com/t51.2885-15/s640x640/sh0.08/e35/12729405_224148847934280_1450226662_n.jpg?ig_cache_key=MTE5MzA1MjU1NDMxOTg0NDA1Nw%3D%3D.2",
"width": 640,
"height": 640
}
},
"users_in_photo": [],
"caption": {
"created_time": "1456442969",
"text": "Bitch! I'm fabulous! That's my case worker..she is obsessed with cats\n\n#cats #caseworker #homestuck",
"from": {
"username": "strider_inc",
"profile_picture": "https://scontent.cdninstagram.com/t51.2885-19/s150x150/12558836_953196128050469_1739102_a.jpg",
"id": "2322171747",
"full_name": "WE All 4EVER KAWAII TRASH GODS"
},
"id": "1193052563471815092"
},
"user_has_liked": false,
"id": "1193052554319844057_2322171747",
"user": {
"username": "strider_inc",
"profile_picture": "https://scontent.cdninstagram.com/t51.2885-19/s150x150/12558836_953196128050469_1739102_a.jpg",
"id": "2322171747",
"full_name": "WE All 4EVER KAWAII TRASH GODS"
}
}
So when I do that I get like 10-12 different pojo classes into which I should map this data. Now firstly...Im just trying that out and Im 100% Ill have some problem mapping them I mean gson will do it for me but i dont know if there are any more that I would need etc.
but most importantly my app only needs the low standard url pictures all the other information is useless for me.
Ofcourse, I know one way to do it which is to convert the whole thing into a string and parse the whole string through multiple times looking for key words etc and making images etc. I dont want to do that because its ugly. It works but I want a concise way of doing that at the same time without mapping completely.
Using Gson's JsonParser class, you can parse your JSON into a tree of JsonElements, and then extract just the data that you need.
For example, in order to print out all the low resolution URLs, you could use the following code:
String json = "...";
JsonParser parser = new JsonParser();
JsonObject object = parser.parse(json).getAsJsonObject();
JsonArray data = object.getAsJsonArray("data");
for (JsonElement element : data) {
JsonObject images = element.getAsJsonObject().getAsJsonObject("images");
JsonObject lowResolution = images.getAsJsonObject("low_resolution");
String url = lowResolution.getAsJsonPrimitive("url").getAsString();
System.out.println(url);
}
Using your example JSON, this would print:
https://scontent.cdninstagram.com/t51.2885-15/s320x320/e35/12729405_224148847934280_1450226662_n.jpg?ig_cache_key=MTE5MzA1MjU1NDMxOTg0NDA1Nw%3D%3D.2