Jackson: add key identifier to the JsonArray - java

I am creating JsonArray with the aid of jackson and I am trying to add a key map_data to the craeted JsonArray to send it as response to the Android app. How can I add it to the JsonArray?
I appreaciate any help.
{
"map_data":
[
{"route": 2, "latitude": 89.667781, "longitude": 13.517741},
{"route": 7, "latitude": 89.657772, "longitude": 13.537742},
{"route": 9, "latitude": 89.647763, "longitude": 13.547754},
{"route": 12, "latitude":89.637754, "longitude": 13.567765}
]
}
Code:
Database db = new Database();
List<MapData> lrl = db.get_map_data(selected);
try {
ObjectWriter ow = new ObjectMapper().writer()
.withDefaultPrettyPrinter();
String json = ow.writeValueAsString(lrl);
System.out.println("The output of json: " + json);
}

You can use ObjectWriter#withRootName(String) to give a root name
Method for constructing a new instance with configuration that
specifies what root name to use for "root element wrapping".
For example,
String json = ow.withRootName("map_data").writeValueAsString(lrl);

What you want as a result is a JSON object, containing a single field named map_data of type array. So that's what you should serialize instead of just serializing a list:
public class SomeClass {
#JsonProperty("map_data")
private List<MapData> mapData;
// getters and setters omitted for brevity
}

Related

Remove a String from Json Object

I am trying to convert an Avro Kafka Event to Json and need to manipulate The Avro Event by Removing Strings from this Event.
I am using GSON Library to manipulate the Json String Object but somehow its not removing the intended String.
JsonElement je = new Gson().fromJson(matchRequest, JsonElement.class);
JsonObject jo = je.getAsJsonObject();
jo.remove("com.XXX.XXXX");
jo.remove("com.XXX.XXX");
jo.remove("com.XXX.XXX");
System.out.println("#################"+jo);
Json String I am Receiving as matchRequest is
{"interaction_id":"321","customer_id":"32","context_id":"123","work_id":"ewq","work_request_id":"213","task_type":"123","match_type":"wert","resource_list":{"com.xxx.xxxx":{"rank":1,"resource_data":{"com.xxx.xxxx":{"account_id":1,"source_name":"Mankind","channel_id":"voice"}}}},"service_list":{"com.xxx.xxxx":{"rank":5,"priority":1,"resource_count":"gvk","min_proficiency":"10","max_proficiency":"1","attributes":{"com.xxx.xxxx":{"category":"edw","value":"33232"}},"resource_offered":{"com.xxx.xxxx":{"agent_id":"rewq","account_id":"123","source_name":"wqe","resource_address":"ewq","source_address":"rewq","channel_id":"212","channel_provider":"wqe"}}}},"matching_state":"OFFERED"}
JSON Format
"interaction_id": "321",
"customer_id": "32",
"context_id": "123",
"work_id": "ewq",
"work_request_id": "213",
"task_type": "123",
"match_type": "wert",
"resource_list": {
"com.XXXXXX": {
"rank": 1,
"resource_data": {
"com.XXXX": {
"account_id": 1,
"source_name": "Mankind",
"channel_id": "voice"
}
}
}
},
"service_list": {
"com.XXXX": {
"rank": 5,
"priority": 1,
"resource_count": "gvk",
"min_proficiency": "10",
"max_proficiency": "1",
"attributes": {
"com.XXXX": {
"category": "edw",
"value": "33232"
}
},
"resource_offered": {
"com.XXXX": {
"agent_id": "rewq",
"account_id": "123",
"source_name": "wqe",
"resource_address": "ewq",
"source_address": "rewq",
"channel_id": "212",
"channel_provider": "wqe"
}
}
}
},
"matching_state": "OFFERED"
}
When you look at the documentation of the remove() method, it needs a key from the JSON object in parameter.
However, the JSON you are receiving does not contain "com.xxx.xxxx" as key, but some keys, like "resource_list", are linked to another JSON object containing "com.xxx.xxxx" as a key.
You may want to look recursively into the JSON object you receive to remove the intended String.
You need to perform your operation over your array:
jo.getAsJsonObject("resource_list").remove("com.XXX.XXXX");
This should do the trick.

Parsing JSON object from service call Spring JAVA

I am getting the following response from some service call . I am trying to parse the JSON . I am actually new to JAVA and not sure about how to parse JSON objects returned from HTTP call . I am getting the following error :
org.json.JSONException: JSONArray initial value should be a string or collection or array.
at org.json.JSONArray.<init>(JSONArray.java:197) ~[json-20180813.jar!/:na]
Code :
Object resp = hiveApiClient.getEnrollmentSearchDetails(certificate, employeeId);
logger.info("response : " + resp);
JSONArray mainArray = new JSONArray(resp);
// The nested array is at the second position : 1
JSONArray nestedArray = mainArray.getJSONArray(1);
// the interesting main JSONObject is on the first position
// of the nested array : 0
JSONObject interestingJSONObject = nestedArray.getJSONObject(0);
logger.info("XXX :{}", interestingJSONObject);
String courseId = interestingJSONObject.getJSONObject("additionalData").getString("courseId");
logger.info("XXXX :{}",courseId);
return courseId;
Response :
[
"list", [{
"#type": "com.saba.services.calendar.CalendarElementDetail",
"eventType": "ILTCLASS",
"elementName": "Microservice Application Architecture",
"elementId": "class000000000013497",
"eventId": "timel000000000103609",
"ownerID": "emplo000000000096641",
"locationId": "locat000000000003165",
"locationName": "IND-Bangalore-Karnataka",
"additionalData": {
"#type": "map",
"locationTimeZone": "tzone000000000000042",
"eventID": "class000000000013497",
"locationName": "IND-Bangalore-Karnataka",
"locationId": "locat000000000003165",
"transcriptID": "ofapr000000002962367",
"registrationID": "regdw000000001766254",
"eventName": "Microservice Application Architecture",
"moduleID": "regmd000000002147176",
"courseID": "cours000000000031995"
},
"startDate": {
"#type": "com.saba.customtypes.DateWithLocale",
"date": 1538613000000,
"locale": "03-OCT-2018",
"timeInLocale": "8:30 PM",
"dateInUserTimeZone": "03-OCT-2018",
"timeInUserTimeZone": "5:30 PM",
"dateInCustomTimeZone": null,
"timeInCustomTimeZone": null,
"customTimeZoneDate": 0,
"timeInStandardFormat": "8:30 PM",
"dateInStandardFormat": "10/03/2018"
}
}]
]
Well first of all, your json is not valid because of this}:
["list" : /* something here but anyway, not the concern here */ ]
when it should have been
{"list" : /* something here but anyway not the concern here */}
I think your problem is with the understanding of how a JSON file works and what is a json object and a json array. Please correct your JSON input so that we can provide you with insights on how to retrieve the value you need.
Additionally, I would recommend you looking into Jackson lib for parsing JSON objects to JAVA POJOs directly really easily. The link is a great tutorial to get you started here. Furthermore, jackson is already included with Spring so that you literally have nothing to install.
Edit
I misread the JSON input : I saw a : after "list" instead of a ,.
So your JSON is a proper JSON but its a quite uncommon JSON as it is loosely typed and therefore cannot be that easily parsed with standard Jackson library for example. In fact, in the main array, a string is put together with a Json Object which is a very bad practice but that's not your fault as I suppose you are not responsible for the output of this HTTP call.
So how can you actually get your value ? Well let's describe the JSON, you've got here : a JSON array containing a String and another sub JSON array. You want to take some values from the very first JSON object inside the nested json array.
This one :
{
"#type": "com.saba.services.calendar.CalendarElementDetail",
"eventType": "ILTCLASS",
"elementName": "Microservice Application Architecture",
"elementId": "class000000000013497",
"eventId": "timel000000000103609",
"ownerID": "emplo000000000096641",
"locationId": "locat000000000003165",
"locationName": "IND-Bangalore-Karnataka",
"additionalData": {
"#type": "map",
"locationTimeZone": "tzone000000000000042",
"eventID": "class000000000013497",
"locationName": "IND-Bangalore-Karnataka",
"locationId": "locat000000000003165",
"transcriptID": "ofapr000000002962367",
"registrationID": "regdw000000001766254",
"eventName": "Microservice Application Architecture",
"moduleID": "regmd000000002147176",
"courseID": "cours000000000031995"
},
"startDate": {
"#type": "com.saba.customtypes.DateWithLocale",
"date": 1538613000000,
"locale": "03-OCT-2018",
"timeInLocale": "8:30 PM",
"dateInUserTimeZone": "03-OCT-2018",
"timeInUserTimeZone": "5:30 PM",
"dateInCustomTimeZone": null,
"timeInCustomTimeZone": null,
"customTimeZoneDate": 0,
"timeInStandardFormat": "8:30 PM",
"dateInStandardFormat": "10/03/2018"
}
}
The first task here is to gather this object. Let's suppose the nested json array is always in the second position after the string and that the JSON object you want is always at the first position of the nested array which might not be the case depending on your input JSON but this was not precised in your question.
JSONArray mainArray = new JSONArray(resp);
// The nested array is at the second position : 1
JSONArray nestedArray = mainArray.getJSONArray(1);
// the interesting main JSONObject is on the first position
// of the nested array : 0
JSONObject interestingJSONObject = nestedArray.getJSONObject(0);
So now we want "courseId" from "additionnalData" Json Object :
String courseId = interestingJSONObject.getJSONObject("additionalData").getString("courseId");
And there you go!

Trouble parsing a json array inside a json array

I am having trouble parsing a simple json in java. Here is the sample json.
[
{
"politics": [
{
"type": "admin2",
"friendly_type": "country",
"name": "United States",
"code": "usa"
},
{
"type": "admin6",
"friendly_type": "county",
"name": "Gratiot",
"code": "26_057"
},
{
"type": "constituency",
"friendly_type": "constituency",
"name": "Eighth district, MI",
"code": "26_08"
},
{
"type": "admin6",
"friendly_type": "county",
"name": "Clinton",
"code": "26_037"
},
{
"type": "admin4",
"friendly_type": "state",
"name": "Michigan",
"code": "us26"
},
{
"type": "constituency",
"friendly_type": "constituency",
"name": "Fourth district, MI",
"code": "26_04"
}
],
"location": {
"latitude": 43.111976,
"longitude": -84.71275
}
}
]
Now this gives me the correct json index.
JSONParser parser = new JSONParser();
Object obj = parser.parse(output);
JSONArray array = (JSONArray)obj;
String jsonobj = array.get(0).toString();
{"politics":[{"code":"usa","name":"United States","type":"admin2","friendly_type":"country"},{"code":"26_057","name":"Gratiot","type":"admin6","friendly_type":"county"},{"code":"26_08","name":"Eighth district, MI","type":"constituency","friendly_type":"constituency"},{"code":"26_037","name":"Clinton","type":"admin6","friendly_type":"county"},{"code":"us26","name":"Michigan","type":"admin4","friendly_type":"state"},{"code":"26_04","name":"Fourth district, MI","type":"constituency","friendly_type":"constituency"}],"location":{"latitude":43.111976,"longitude":-84.71275}}
But I cant seem to get the attribute that I want from it.
JSONObject obj1 = new JSONObject(jsonobj);
String n = obj1.getString("admin4");
System.out.println(n);
All that I need from this json is the state which is Michigan. Where am I wrong?
Help would be really appreciated.
First, array.get(0) will get you the first element from the main array. This first element is a JSON object that has two properties politics and location. You seem to be interested in a value that is inside the array value of the politics property. You'll have to use this ((JSONArray)((JSONObject)array.get(0)).get("politics")) to get that array.
Second, admin4 is not a property it is actually a value of the type property. You'll have to loop through the array to find it.
Here is a complete example:
JSONParser parser = new JSONParser();
Object obj = parser.parse(output);
JSONArray array = (JSONArray)obj;
JSONArray politics = ((JSONObject)array.get(0)).get("politics"));
JSONObject obj = null;
for(int i = 0; i < politics.size(); i++){
if(((JSONObject)politics.get(i)).getString("type").equals("admin4")){
obj = ((JSONObject)politics.get(i));
}
}
if(obj != null){
// Do something with the object.
}
It seems that you're using the simple json library. I don't remember exactly if it is .get("politics") or .getJSONObject("politics"). There may be other mistakes in method names in my example.
the best solution to simplify your search and other operations on json object, is the convert json string to java object and doing your operations.
for convert json string to java object use follow code:
import org.codehaus.jackson.map.ObjectMapper;
import org.json.JSONException;
import org.json.JSONObject;
YourObject myObject;
ObjectMapper mapper = new ObjectMapper();
try{
myObject= mapper.readValue(jsonData, myObject.class);
}
catch (Exception e) {
e.printStackTrace();
}
for example define your class ass follow :
public class myObject{
private List<Politics> politics;
private Location location;
// define getters and setters
}
define Politics and Location class:
public class Politics
{
String type;
String friendly_type;
String name;
String code;
// define getters and setters
}
public class Location
{
String latitude;
String longitude;
// define getters and setters
}
It's because your are trying to get the inner element of the JSON Object.
try
JSONObject obj1 = new JSONObject(jsonobj);
JSONArray arr = (JSONArray) obj1.getObject("politics");
You will get a JSONArray object which further constitutes of JSON objects.
Now in order to get values using the key you must iterate array as given below:
for(int i=0; i<arr.size(); i++){
JSONObject obj = arr.getJSONArray(i);
System.out.println(obj.getString("type"));
}
which will now provide you with output:
admin2
admin6
constituency
admin6
admin4
constituency

JAXB: Unmarshal heterogeneous array

I'm trying to unmarshal using MOXy a json with the following structure:
[
{
"page": 1,
"pages": 1
},
[
{
"indicator": {
"id": "IC.BUS.EASE.XQ",
"value": "Ease of doing business index"
},
"country": {
"id": "1A",
"value": "Arab World"
},
"value": "113.952380952381",
"date": "2014"
},
...
]
]
The first element of the array is an object and the second element is another array of complex elements. I've really searched here at SO and the MOXy documentation for a simmilar example without any success.
My best attempt at mapping the json document to JAVA classes is as follows. The root class is CountryDataResponse (getters & setters ommited):
#XmlRootElement
#XmlType(propOrder ={"paginationInfo", "dataArray"})
public class CountryDataResponse {
private DataArray dataArray;
private PaginationInfo paginationInfo;
}
(I can see this is going to fail, because it isn't an array, but I'm completly lost.)
PaginationInfo class models the first element of the root array and DataArray class wraps the second element, which is an Array of Data class elements. Additionally, I've created the Indicator and Country classes for the complex types inside each Data element.
The main classes (Indicator and Country ommited):
#XmlRootElement(name = "paginationInfo")
#XmlAccessorType(XmlAccessType.FIELD)
public class PaginationInfo {
private int page;
private int pages;
}
#XmlRootElement( name = "dataArray" )
public class DataArray {
List<Data> datas;
}
#XmlRootElement(name="data")
#XmlAccessorType(XmlAccessType.FIELD)
public class Data {
private Indicator indicator;
private Country country;
private String date;
private double value;
}
Now, debugging the following code:
public static void main(String args[]) {
String test = "[{\"page\": 1,\"pages\": 1,\"per_page\": \"1000\",\"total\": 248},"
+ "["
+ "{\"indicator\": {\"id\": \"NY.GDP.MKTP.CD\",\"value\": \"GDP (current US$)\"},"
+ "\"country\": {\"id\": \"1A\",\"value\": \"Arab World\"},"
+ "\"value\": \"2853079422103.94\","
+ "\"decimal\": \"1\","
+ "\"date\": \"2013\"},"
+ "{\"indicator\": {\"id\": \"NY.GDP.MKTP.CD\",\"value\": \"GDP (current US$)\"},"
+ "\"country\": {\"id\": \"S3\",\"value\": \"Caribbean small states\"},"
+ "\"value\": \"67033118185.1864\","
+ "\"decimal\": \"1\","
+ "\"date\": \"2013\"}"
+ "]]";
JAXBContext jc = JAXBContext.newInstance(CountryDataResponse.class, Country.class, Data.class, DataArray.class, Indicator.class, PaginationInfo.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, MediaType.APPLICATION_JSON);
unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false);
Object res = unmarshaller.unmarshal(json, CountryDataResponse.class);
}
The res object (of class JAXBElement) has a value of type ArrayList. The first element of the array is an object of class CountryDataResponse (it should be PaginationInfo), the second is another ArrayList with elements of class CountryDataResponse, too (they should be Data instances).
Can anyone help me, please, or it is simply a malformed json and it can't be automatically unmarshalled correctly?
Thank you in advance.
Although the JSON is valid I would suggest changing the structure, something along the lines of:
{
"paginationInfo": {
"page": 1,
"pages": 1
},
"dataArray": [
{
"indicator": {
"id": "IC.BUS.EASE.XQ",
"value": "Ease of doing business index"
},
"country": {
"id": "1A",
"value": "Arab World"
},
"value": "113.952380952381",
"date": "2014"
}
]
}
This will allow you to extract the data you wish using the 'key' name which is how JSON is intended to be used.
Another approach would be to embed the data array within the paged object:
{
"page": 1,
"pages": 1,
"dataArray": [
{
"indicator": {
"id": "IC.BUS.EASE.XQ",
"value": "Ease of doing business index"
},
"country": {
"id": "1A",
"value": "Arab World"
},
"value": "113.952380952381",
"date": "2014"
}
]
}
This approach would allow you to create a generic page wrapper which could come in useful if you have multiple formats you would like to page.
Hope this helps.
Thanks to a MOXy's feature added in version 2.6, it's possible to unmarshal from javax.json.JsonStructure, javax.json.JsonObject and javax.json.JsonArray.
Using this feature I've managed to unmarshal the different parts of the original JSON to two objects: a PaginationInfo instance and an ArrayList of Data. These objects can then be used to configure an instance of CountryDataResponse, although it wouldn't be necessary as this class was created only to try to unmarshal directly from the JSON, in the first place.
public static CountryDataResponse javaSevenMode(String jsonString)
throws PropertyException, JAXBException {
Unmarshaller unmarshaller = JAXB_CONTEXT.createUnmarshaller();
unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, MediaType.APPLICATION_JSON);
unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false);
StringReader sr = new StringReader(jsonString);
JsonReader jsonReader = Json.createReader(sr);
JsonArray rootArray = jsonReader.readArray();
JsonObject paginationInfoJO = rootArray.getJsonObject(0);
JsonStructureSource paginationInfoJSS = new JsonStructureSource(paginationInfoJO);
PaginationInfo pi = unmarshaller.unmarshal(paginationInfoJSS, PaginationInfo.class).getValue();
JsonArray dataJArray = rootArray.getJsonArray(1);
JsonStructureSource dataArrayJSS = new JsonStructureSource(dataJArray);
List<Data> datas
= (List<Data>) unmarshaller.unmarshal(dataArrayJSS, Data.class)
.getValue();
DataArray da = new DataArray();
da.setDatas(datas);
CountryDataResponse cdr = new CountryDataResponse();
cdr.setDataArray(da);
cdr.setPaginationInfo(pi);
return cdr;
}
Thanks to #blaise-doughan for inspiration (see http://blog.bdoughan.com/2013/07/eclipselink-moxy-and-java-api-for-json.html)

JSON different objects in an array

At the moment i'm trying to understand json and how it works.
But i have a problem with an array of objects.
all objects in the array have a key called "value" (i know it's weird, it's not my code) what also is an object.
And now to the problem: This object called "value" has always different key-values.
So i dont now how i can parse the json code to java object code, when it differ, every time.
Here some examples:
First object of the array:
"value":
{
"local":
[
"English", "Deutsch", Espanol"
],
"english":
[
"English", "Deutsch", Espanol"
],
},
Second object(now a string, not object) of the array:
"value" : "",
Third object of the array:
"value" : {},
...
Maybe I'm doing the parsing wrong.
First I have created the beans classes in java for the json code and then I'm using the automatic parser of google. (gson)
It works when only one of the examples above is inside the json code. (it should not differ, like changing from string to object...)
Gson gson = new Gson();
Output output = gson.fromJson(json, Output.class);
Output is the main class for the json stuff.
I have found out that maybe while parsing I could check a value called "id" first, and from that I could create another beans class with the right variables ...
Thats the code i need to parse to java objects and how do you do that??
The problem is the key called "value", because its always different.
With my method of using the google parser "gson" it wont work, because i'm getting exception that its an string but i was waiting for an object...
{
"status":"success",
"data":{
"panel":{
"title":{
"label":{ "local":"Tote Selection", "english":"Tote Selection" },
"image":"public/img/pick.jpg", "type":"default"
},
"isFirst":false, // currently not used
"isLast":false, // currently not used
"ownCount":0, // currently not used
"panelsCount":0, // currently not used
"elements":[
{
"type":"text",
"id":"1", "value":{ "local":"Scan next order tote",
"english":"Scan next order tote" },
"label":{ "local":"", "english":"" }, "color":"000000",
"fontsize":18, "fontstyle":"flat", "alignment":"left",
"rows":"undefined", "bgcolor":"", "isFocus":false
},
{
"type":"text",
"id":"4", "value":{ "local":"Scan tote: ", "english":"Scan tote: " },
"label":{ "local":"", "english":"" }, "color":"000000", "fontsize":20,
"fontstyle":"strong", "alignment":"left", "rows":"undefined",
"bgcolor":"", "isFocus":false
},
{
"type":"input",
"id":"6", "value":"", "label":{ "local":"", "english":"" },
"color":"000000", "fontsize":24, "fontstyle":"flat", "alignment":"left",
"rows":"undefined", "isFocus":true
},
{
"type":"button",
"id":"1", "value":{ "local":"", "english":"" },
"label":{ "local":"Menu", "english":"Menu" }, "color":"000000",
"fontsize":14, "fontstyle":"strong", "alignment":"left",
"rows":"undefined", "isFocus":false
},
{
"type":"button",
"id":"4", "value":{ "local":"", "english":"" },
"label":{ "local":"Enter", "english":"Enter" }, "color":"000000",
"fontsize":14, "fontstyle":"strong", "alignment":"right",18
"rows":"undefined", "isFocus":false
}
]
},
"authToken":"0fdd440a-619f-4936-ab74-d189accb5bd9",
"routing":{
"controller":"panel",
"action":"process",
"workflowId":"singlepicking",
"taskId":"orderSelection"
}
}
}
Thank you for your help!
it looks a little bit different but your answer helped me! Thx
JsonParser parser = new JsonParser();
JsonObject obj = parser.parse(br).getAsJsonObject();
//now getting all the json values
String status = obj.get("status").getAsString();
JsonObject data = obj.getAsJsonObject("data");
String authToken = data.get("authToken").getAsString();
JsonObject routing = data.getAsJsonObject("routing");
String controller = routing.get("controller").getAsString();
String action = routing.get("action").getAsString();
String workflowId = routing.get("taskId").getAsString();
If I understood ur question properly u can retrieve the values of the JSONArray as below
for (int i = 0; i < JArray.length(); i++) {
print(JArray.getJSONObject(i).tostring())
}
So if i am right u are getting the JSON from a String First?? so please try below first store the String in JSONObject as JSONObject obj = new JSONObject(str);//str is the string that u are getting
to get the valueenglish that are in data-panel-tittle-label is
String englishinLable=obj .getJSONObject("data").getJSONObject("panel").getJSONObject("title").getJSONObject("label").optString("english")

Categories

Resources