Convert a Json Array to Map in java - java

I am working on a project where I get a JSON response from my API using entities and DTO
Folowing is the response:
return XXXResponseDTO
.builder()
.codeTypeList(commonCodeDetailList)
.build();
commonCodeDetailList list contains the data from the database. Final output will be
{
"code_type_list": [
{
"code_type": "RECEIVING_LIST",
"code_list": [
{
"code": "1",
"code_name": "NAME"
},
{
"code": "2",
"code_name": "NAME1"
}
],
"display_pattern_list": [
{
"display_pattern_name": "0",
"display_code_list": [
"1",
"2"
]
}
]
},
{
"code_type": "RECEIVING_LIST1",
"code_list": [
{
"code": "1",
"code_name": "NAME"
}
],
"display_pattern_list": [
{
"display_pattern_name": "0",
"display_code_list": [
"1"
]
}
]
}
]
}
I need to convert this to Map with key-value pairs. How could I achieve this?

Using Jackson, you can do the following:
ObjectMapper mapper = new ObjectMapper();
String jsonStr = mapper.writeValueAsString(commonCodeDetailList);
Map<String, String> map = mapper.readValue(jsonStr, Map.class);
First you need to convert commonCodeDetailList into a json string. After that you can convert this json string to map.

Related

How to deep select Nodes based on given depth in Java?

I have json representation like below:
{
"total": "555",
"offset": "555",
"hasMore": "false",
"results": [
{
"associations": {
"workflowIds": [],
"companyIds": [],
"ownerIds": [],
"child": {
"name" : "association1",
"key" : "a1"
},
"quoteIds": [],
"contentIds": [],
"dealIds": [],
"contactIds": [
4646915
],
"ticketIds": []
},
"scheduledTasks": [
{
"taskType": "REMINDER",
"portalId": 214129,
"engagementType": "TASK",
"engagementId": 6604524566,
"timestamp": 1586815200000
}
]
},
{
"associations": {
"workflowIds": [],
"companyIds": [],
"ownerIds": [],
"quoteIds": [],
"contentIds": [],
"child": {
"name" : "association2",
"key" : "a2"
},
"dealIds": [],
"contactIds": [
4646915
],
"ticketIds": []
}
},
{
"associations": {
"workflowIds": [],
"companyIds": [],
"ownerIds": [],
"quoteIds": [],
"contentIds": [],
"dealIds": [],
"child": {
"name" : "association3",
"key" : "a3"
},
"contactIds": [
3995065
],
"ticketIds": []
}
},
{
"associations": {
"workflowIds": [],
"companyIds": [],
"ownerIds": [],
"quoteIds": [],
"contentIds": [],
"dealIds": [],
"contactIds": [
4648365
],
"ticketIds": []
}
}
]
}
I would like to get filtered information (something like sql) of given node by passing node selector string , to achieve this I am doing like below:
ObjectMapper objectMapper = new ObjectMapper();
JsonNode root = objectMapper.readTree(new File("/Users/pra/automation/foo.json"));
String result = root.at("/results/0/associations/0/child").toString();
Assert.assertNotNull(result);
and this code is working as well, it filters first nodes out of array because 0 level index is passed, but I need output for all matching elements, so as to achieve that I passed * instead of 0 but it is not working.
means i am trying something like below ( which is failing ):
String result = root.at("/results/*/associations/*/child").toString();
Desired Output that needed:
[
{
"name" : "association1",
"key" : "a1"
},
{
"name" : "association2",
"key" : "a2"
},
{
"name" : "association3",
"key" : "a3"
}
]
I am open for other java based alternatives to achieve this. Thanks.
If you may switch to Gson library you may use im.wilk.vor:Voritem library gitHub or in Maven repository.
VorItem vorItemFactory = VorItemFactoryBuilder.standard.build();
JsonElement je = JsonParser.parse(...)
VorItem vi = vorItemFactory.from(je);
VorItem result = vorItemFactory.empty();
for (int idx = 0; idx < vi.get("result").list().size(); idx++) {
result.get(idx).set("name", vi.get("result").get(idx).get("associations/child/name");
result.get(idx).set("key", vi.get("result").get(idx).get("associations/child/key");
}
return result.asJsonElement().toString();
I found Andreas suggestion to be very effective and usage friendly, I was able to achieve desired output by using JSONPath library .
Usage code is as follows:
ObjectMapper objectMapper = new ObjectMapper();
String root = objectMapper.readTree(new File("/Users/pramo/automation/foo.json")).toString();
List<Object> associations = JsonPath.read(root, "$.results[*].associations.child");

Recover field Json 2 array level gson or Jackson

I have this Json and i can´t recover the field "entidad" and "oficina":
{
"resultado": [
{
"columa": [
"p"
],
"datos": [
{
"row": [
{
"oficina": "0000",
"entidad": "1234",
"nombre": "nombre persona"
}
],
"meta": [
{
"id": 4700925,
"type": "node",
"deleted": false
}
]
}
]
}
],
"errors": [],
"responseTime": 84
}
How can I recover the field "oficina" and "entidad"?
I could use Gson or Jackson.
I can´t recover this fields.
thank you
Get your array 'row'. When you got it, you can iterate it and extract the elements:
Get resultado --> get datos --> get row, then:
for(int i=0; i<arrayJSON.length; i++) {
JSONObject objectJSON= arrayJSON.get(i);
String entidad = objectJSON.getString("entidad");
String oficina = objectJSON.getString("oficina");
}

JSON to JSON Transform of input sample using any existing java library/tools

Input:
{
"Student": {
"name" :"abc",
"id" : 588,
"class : "12"
}
}
Reqired Output:
{
"Student": {
"key" :"name",
"value":"abc",
"key" :"id",
"value":"588",
"key" :"class",
"value":"12"
}
}
Your output json invalid. Json object can not duplicate key .
You can use the library org.json and do something like this:
JSONObject jsonObject = new JSONObject(inputJson);
JSONObject outputJson = new JSONObject();
JSONArray array = new JSONArray();
for (Object key : jsonObject.keySet()) {
JSONObject item = new JSONObject();
String keyStr = (String)key;
Object keyvalue = jsonObj.get(keyStr);
item.put(keyStr, keyvalue);
array.put(item);
}
outputJson.put("Student", array);
System.out.println(json.toString());
Output :
{
"Student": [
{
"key": "name",
"value": "abc"
},
{
"key": "id",
"value": "588"
},
{
"key": "class",
"value": "12"
}
]
}
Similar to the other answer, the desired output JSON format is not valid.
The closest valid output would be
{
"Student" : [ {
"key" : "name",
"value" : "abc"
}, {
"key" : "id",
"value" : 588
}, {
"key" : "class",
"value" : "12"
} ]
}
This can be generated via Jolt with the following spec
[
{
"operation": "shift",
"spec": {
"Student": {
"name": {
"$": "Student[0].key",
"#": "Student[0].value"
},
"id": {
"$": "Student[1].key",
"#": "Student[1].value"
},
"class": {
"$": "Student[2].key",
"#": "Student[2].value"
}
}
}
}
]
This is easy to solve with JSLT if we assume the output is made valid JSON by making an array of key/value objects like the other respondents do.
The array function converts an object into an array of key/value objects exactly like you ask for, so the transform becomes:
{"Student" : array(.Student)}

How to get specific nodes from a Json Tree without iterating through the entire list

Consider the following Json structure:
{ "ubds": [
{
"id": "33",
"metaData": {
"lineInfo": {
"poNumber": "PO_123",
"poLineNumber": 1
}
},
"confirmedDeliveryDate": "2016-05-26T16:15:51",
"quantity": 99
},
{
"id": "34",
"metaData": {
"lineInfo": {
"poNumber": "PO_123",
"poLineNumber": 2
}
},
"confirmedDeliveryDate": "2016-05-26T16:15:51",
"quantity": 99
},
{
"id": "35",
"metaData": {
"lineInfo": {
"poNumber": "PO_123",
"poLineNumber": 3
}
},
"confirmedDeliveryDate": "2016-05-26T16:15:51",
"quantity": 99
}]}
Using JsonNode, is there a way to get the entire child node {id through quantity} with the poLineNumber attribute value of 3 without having to iterate through all the nodes and returning on a match? Do I need to use JsonPath for this?
You can have a look to JsonPath.
You can first use ObjectMapper to create a Map<String, Object> from the given json string, and read it and evaluate a JsonPath expression. For example:
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> mappedObject = mapper.readValue(jsonString, Map.class);
// Evaluate that expression
Object result = JsonPath.read(mappedObject, "$.ubds[?(#.metaData.lineInfo.poLineNumber==3)]");
or directly read the json string with JsonPath:
Object result = JsonPath.parse(jsonString).read("$.ubds[?(#.metaData.lineInfo.poLineNumber==3)]");

how to get the value of lat and lng from the json

I have a json response.I want to get the value of lat and lng from the json response.But i didn't get the values.Please Help me.Below is my response.
{
"html_attributions": [],
"results": [
{
"geometry": {
"location": {
"lat": 9.493837,
"lng": 76.338506
}
},
"icon": "http://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png",
"id": "2730a3d7ab068d666e61a02ce6160b4cd21a38c7",
"name": "Nagarjuna",
"place_id": "ChIJr0-U4vSECDsRtiALUlgZOzI",
"reference": "CmRcAAAA4yl72_x5llqvdshRJwuuntunXrYu33qdP5G7-I0CdHzcDsyd6wwqjxdNeqvT6vtRIoDoIk_WGNd62SYSoNEdBrpDrOcf5g5eZMj_vobhmF11mrujsQ_Yc7p-oGxQH0XtEhDNJdjQf_WlK_dRAckBzlA3GhQ_wzXs5RxoaxWDSEurm_R5syuovg",
"scope": "GOOGLE",
"types": [
"hospital",
"establishment"
],
"vicinity": "State Highway 40, Kodiveedu, Alappuzha"
},
{
"geometry": {
"location": {
"lat": 9.500542,
"lng": 76.341017
}
},
"icon": "http://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png",
"id": "d5b6c81a53a346dea1263de7a777703bc72b8796",
"name": "SYDNEY OPTICALS",
"opening_hours": {
"open_now": true,
"weekday_text": []
},
"photos": [
{
"height": 422,
"html_attributions": [],
"photo_reference": "CnRnAAAA_jg-NlSrVKkDOP7wXhPhvFTD8NW4A4aDI_Ptl3F9c_qt9QwdztNTG9Cr51uGIphpEUMyhsTfhhaa-TlfoL8MUEffbguZJ1AhKUwzfe7Mbrvm2KW8Y1EQXVw_3FglxA4LM1hqWJCK_AV4xcvOw1vuHRIQ8_keBYr29H8jK145RQ_PkRoUgPZ0qzcSNdIntc2ZI4WvBIR-TBQ",
"width": 630
}
],
"place_id": "ChIJl9tvIV6ECDsR7Cmf3KkIl-4",
"reference": "CnRjAAAA3qhFUcb8P9akE8xw-KwfF6OU6qvy2cVX4Sg0qK_xCOfeUEyxoFgwof8rk-Z2BBJ7Z4m7ZTbfdp78wqFbeLfojQWPldq7XDfzX0pLScBSysebEp9P4XmrsAO5qyqSUveb5jWcJDkYiOLKgaKMzoWQphIQbldrdJ9iEDHkGiQ7tleNYxoUnjcjcynUDMftaErRUQbOn-GkWj0",
"scope": "GOOGLE",
"types": [
"store",
"hospital",
"health",
"establishment"
],
"vicinity": "Mullakkal, Alappuzha"
}
],
"status": "OK"
}
This is the google api response i used for getting the list of hospitals.Anybode plese help me.Thanks in advance.
Use these steps:
Create a model class for that Json Response
Use Gson to parse the response
Then create an object of the class
using the object get the data variable from the class
I hope I can help.
First, validate your JSON with http://jsonlint.com/
Second, use this site to generate POJO: http://www.jsonschema2pojo.org/
make sure that Annotation GSON and Source type JSON are clicked ON!
Copy your classes in to your project.
Third: use GSON in Android :) (Retrofit is good for this)
Supposing you use the json.org Implementation for Java:
String response = "{\"html_attributions\": [], \"results\": ...";
JSONObject jo = new JSONObject(response);
JSONObject result = jo.getJSONArray("results").getJSONObject(0);
JSONObject location = result.getJSONObject("geometry").getJSONObject("location");
double lat = location.getDouble("lat");
double lng = location.getDouble("lng");
try this
String response = "{\"html_attributions\": [], \"results\": ...";
JSONObject objResponce = new JSONObject(response);
JSONArray arrayResults=new JSONArray(objResponce.getString("results"));
if(arrayResults.length()>0)
{
for(int i=0;i<arrayResults.length();i++)
{
//--- get each json object from array -----
JSONObject objArrayResults = arrayResults.getJSONObject(i);
//--- get geometry json object from each object of array -----
JSONObject objGeometry=new JSONObject(objArrayResults.getString("geometry"));
//--- get location json object from geometry json object -----
JSONObject objLocation=new JSONObject(objGeometry.getString("location"));
System.out.println("Latitude :"+objLocation.getString("lat"));
System.out.println("Longitude :"+objLocation.getString("lng"));
}
}

Categories