Reading a json using jackson - java

I'm having trouble reading this json, the code seems to work, but there's 2 problems
It only reads one block of the json, not entirely.
It always has "null" as a value in the properties.
I've been trying to show the json organized in the console, but when i try those 2 things happens.
Sample of the JSON data:
{
"RestResponse" : {
"messages" : [ "More webservices are available at http://www.groupkt.com/post/f2129b88/services.htm", "Total [249] records found." ],
"result" : [ {
"name" : "Afghanistan",
"alpha2_code" : "AF",
"alpha3_code" : "AFG"
}, {
"name" : "Ă…land Islands",
"alpha2_code" : "AX",
"alpha3_code" : "ALA"
}, {
"name" : "Albania",
"alpha2_code" : "AL",
"alpha3_code" : "ALB"
}, ...
]
}
}
My code:
public class jsonController {
public void run() {
ObjectMapper mapper = new ObjectMapper();
try {
jsonHandler obj = mapper.readValue(new URL("http://services.groupkt.com/country/get/all"), jsonHandler.class);
//Organized Print
String organizedprint = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
System.out.println(organizedprint);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
And in the main i've got
jsonController obj = new jsonController();
obj.run();
And here's the jsonHandler
#JsonIgnoreProperties(ignoreUnknown=true)
public class jsonHandler {
private String restResponse;
private String messages;
private String result;
private String name;
private String alpha2;
private String alpha3;
}
Any idea what I'm doing wrong?

You declared your data types incorrectly in your model. Your Java code declares that the data will have a single object containing 6 string attributes. The JSON data provided by the server is not like that at all. For example, messages is a list of strings and result is a list of objects, not a string. You need to declare your Java model accordingly.
For example:
public class jsonHandler
{
private RestResponseStructure restResponse;
}
public class RestResponseStructure
{
private List<String> messages;
private List<CountryRecord> results;
}
public class CountryRecord {
private String name;
private String alpha2_code;
private String alpha3_code;
}

Okay your mapping class, jsonHandler is wrong. First of all, it should be capitalized correctly (JsonHandler)
Using http://www.jsonschema2pojo.org/ i generated a better model. It's composed of 3 classes. Simply change the package "com.example" to yours.
package com.example;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({
"RestResponse"
})
public class JsonHandler {
#JsonProperty("RestResponse")
private RestResponse restResponse;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
#JsonProperty("RestResponse")
public RestResponse getRestResponse() {
return restResponse;
}
#JsonProperty("RestResponse")
public void setRestResponse(RestResponse restResponse) {
this.restResponse = restResponse;
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
com.example.RestResponse.java
package com.example;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({
"messages",
"result"
})
public class RestResponse {
#JsonProperty("messages")
private List<String> messages = null;
#JsonProperty("result")
private List<Result> result = null;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
#JsonProperty("messages")
public List<String> getMessages() {
return messages;
}
#JsonProperty("messages")
public void setMessages(List<String> messages) {
this.messages = messages;
}
#JsonProperty("result")
public List<Result> getResult() {
return result;
}
#JsonProperty("result")
public void setResult(List<Result> result) {
this.result = result;
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
com.example.Result.java
package com.example;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({
"name",
"alpha2_code",
"alpha3_code"
})
public class Result {
#JsonProperty("name")
private String name;
#JsonProperty("alpha2_code")
private String alpha2Code;
#JsonProperty("alpha3_code")
private String alpha3Code;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
#JsonProperty("name")
public String getName() {
return name;
}
#JsonProperty("name")
public void setName(String name) {
this.name = name;
}
#JsonProperty("alpha2_code")
public String getAlpha2Code() {
return alpha2Code;
}
#JsonProperty("alpha2_code")
public void setAlpha2Code(String alpha2Code) {
this.alpha2Code = alpha2Code;
}
#JsonProperty("alpha3_code")
public String getAlpha3Code() {
return alpha3Code;
}
#JsonProperty("alpha3_code")
public void setAlpha3Code(String alpha3Code) {
this.alpha3Code = alpha3Code;
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}

Related

How to get data from [Object] android

I am getting this response from my Express API Call.
Here's the Response:
{
"responseData": [{
"unitNames": [
"Matrices",
"Complex Numbers"
],
"subject": "maths",
"unitTopics": {
"1": [{
"topicName": "1.1 Introduction",
"topicURL": ""
},
{
"topicName": "1.2 Square Matrix",
"topicURL": ""
}
],
"2": [{
"topicName": "2.1 Numbers",
"topicURL": ""
}
]
}
}]
}
I got the response by using Retrofit in Android. It works great.But it can't parse Objects
Here's my Problem in Android Side.
{
"responseData": [{
"unitNames": [
"Matrices",
"Complex Numbers"
],
"subject": "maths",
"unitTopics": {
"1": [[Object],
[Object]
],
"2": [[Object]
]
}
}]
}
Its showing Object instead of my Data. How to fix this
Here's the Code:
System.out.println(response.body().getResponseData())
String received_data = response.body().getResponseData();
received_data_sub_units_topics_json = new JSONArray("["+received_data+"]");
System.out.println("MAIN2 "+received_data_sub_units_topics_json);
After converting to jsonarray, it shows like this,
{
"responseData": [{
"unitNames": [
"Matrices",
"Complex Numbers"
],
"subject": "maths",
"unitTopics": {
"1": [["Object"],
["Object"]
],
"2": [["Object"]
]
}
}]
}
Please help me with some solutions
For json i always use the library com.fasterxml.jackson.
You can use too org.json.JSONArray, org.json.JSONObject.
Here is an example of each one:
1- jackson
For implements this (is a bit long but you will convert it to java classes, so, you will can edit the values and obtain it more easily than if you use JSONObject), you have to create classes wich has the same structure than your json:
public class principalClass {
ArrayList<ResponseData> responseData;
...
//Getters, setters and constructors
}
public class ResponseData {
public ArrayList<String> unitNames;
public String subject;
public UnitTopics unitTopics;
...
//Getters, setters and constructors
}
public class UnitTopics {
public ArrayList<Topics> first;
public ArrayList<Topics> second;
...
//Getters, setters and constructors
}
public class Topics {
public String topicName;
public String topicURL;
...
//Getters, setters and constructors
}
Something like that, and then you use jackson to pass your json to you class principalClass:
ObjectMapper obj= new ObjectMapper();
PrincipalClass principal= obj.readValue(json, PrincipalClass.class);
The second posibility is to convert the values to JSONArray and JSONObject:
JSONObject bodyJSON = new JSONObject(json);
JSONArray responseData = bodyJSON.getJSONArray("responseData");
JSONArray unitNames= responseData.getJSONArray(0);
JSONObject subject= responseData.getJSONObject(1);
...
And if u want, u can loop through a JSONArray:
for (int i = 0; i < unitNames.length(); i++) {
String element = unitNames.getString(i);
}
You can use gson converter with retrofit to convert your json data to java object model class
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
Or you can convert json data to model class like
Gson gson = new Gson();
String jsonInString = "{your json data}";
ResponseModel response= gson.fromJson(jsonInString, ResponseModel.class);
Hey have you tried converting this JSON Object to a POJO.
I'd recommend using:
This website
It saves a lot of time and effort.
These will be your model classes:
package com.example.app;
import java.io.Serializable;
import java.util.List;
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class ResponseDatum implements Serializable
{
#SerializedName("unitNames")
#Expose
private List<String> unitNames = null;
#SerializedName("subject")
#Expose
private String subject;
#SerializedName("unitTopics")
#Expose
private UnitTopics unitTopics;
public ResponseDatum() {
}
public ResponseDatum(List<String> unitNames, String subject, UnitTopics unitTopics) {
super();
this.unitNames = unitNames;
this.subject = subject;
this.unitTopics = unitTopics;
}
public List<String> getUnitNames() {
return unitNames;
}
public void setUnitNames(List<String> unitNames) {
this.unitNames = unitNames;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public UnitTopics getUnitTopics() {
return unitTopics;
}
public void setUnitTopics(UnitTopics unitTopics) {
this.unitTopics = unitTopics;
}
}
package com.example.app;
import java.io.Serializable;
import java.util.List;
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class ResponseObject implements Serializable
{
#SerializedName("responseData")
#Expose
private List<ResponseDatum> responseData = null;
public ResponseObject() {
}
public ResponseObject(List<ResponseDatum> responseData) {
super();
this.responseData = responseData;
}
public List<ResponseDatum> getResponseData() {
return responseData;
}
public void setResponseData(List<ResponseDatum> responseData) {
this.responseData = responseData;
}
}
package com.example.app;
import java.io.Serializable;
import java.util.List;
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class UnitTopics implements Serializable
{
#SerializedName("1")
#Expose
private List<com.example.app._1> _1 = null;
#SerializedName("2")
#Expose
private List<com.example.app._2> _2 = null;
public UnitTopics() {
}
public UnitTopics(List<com.example.app._1> _1, List<com.example.app._2> _2) {
super();
this._1 = _1;
this._2 = _2;
}
public List<com.example.app._1> get1() {
return _1;
}
public void set1(List<com.example.app._1> _1) {
this._1 = _1;
}
public List<com.example.app._2> get2() {
return _2;
}
public void set2(List<com.example.app._2> _2) {
this._2 = _2;
}
}
package com.example.app;
import java.io.Serializable;
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class _1 implements Serializable
{
#SerializedName("topicName")
#Expose
private String topicName;
#SerializedName("topicURL")
#Expose
private String topicURL;
public _1() {
}
public _1(String topicName, String topicURL) {
super();
this.topicName = topicName;
this.topicURL = topicURL;
}
public String getTopicName() {
return topicName;
}
public void setTopicName(String topicName) {
this.topicName = topicName;
}
public String getTopicURL() {
return topicURL;
}
public void setTopicURL(String topicURL) {
this.topicURL = topicURL;
}
}
package com.example.app;
import java.io.Serializable;
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class _2 implements Serializable
{
#SerializedName("topicName")
#Expose
private String topicName;
#SerializedName("topicURL")
#Expose
private String topicURL;
public _2() {
}
public _2(String topicName, String topicURL) {
super();
this.topicName = topicName;
this.topicURL = topicURL;
}
public String getTopicName() {
return topicName;
}
public void setTopicName(String topicName) {
this.topicName = topicName;
}
public String getTopicURL() {
return topicURL;
}
public void setTopicURL(String topicURL) {
this.topicURL = topicURL;
}
}

Need to convert below JSON Object to String JAVA

Need to convert below JSON Object to String JAVA, getting stuck how to do with nested array. Below is the JSON object:
{
"url": "https://www.apple.com",
"defer_time": 5,
"email": true,
"mac_res": "1024x768",
"win_res": "1366X768",
"smart_scroll": true,
"layout": "portrait",
"configs": {
"windows 10": {
"chrome": [
"76",
"75"
],
"firefox": [
"67",
"66"
]
},
"macos mojave": {
"chrome": [
"76",
"75"
],
"firefox": [
"67",
"66"
]
}
}
}
Currently, I am using JSONObject and JSONArray to write the code, but not able to get it proper for nested array.
Any help will be appreciated, many thanks !!
this code will clear everything for you i hope. first to read json file you can open it with stream, them pass stream to JSONObject directly, because it has constructor for doing such trick, or append string from file to StringBuilder, then pass stringbuilder to string to JSONObject.
public static void main(String[] args) {
try(BufferedReader fileReader = new BufferedReader(new FileReader("test.json"))){
String line="";
StringBuilder stringBuilder = new StringBuilder();
while ((line = fileReader.readLine()) !=null){
stringBuilder.append(line);
}
JSONObject jsonObject = new JSONObject(stringBuilder.toString());
// to add single values yo your array.
// you can do something like this
JSONObject config = jsonObject.getJSONObject("configs");
JSONObject macos_mojave = config.getJSONObject("macos mojave");
JSONArray jsonArray = macos_mojave.getJSONArray("chrome"); // this way you will reach the array
jsonArray.put("77"); // then you can add them new values
jsonArray.put("78");
System.out.println(jsonArray.toList()); //will print your array content
} catch (IOException e){
e.printStackTrace();
}
JSONArray jsonArray = new JSONArray(); // this is what you call single values, it is array
jsonArray.put(75);
jsonArray.put(76);
JSONObject jsonObject1 = new JSONObject();
jsonObject1.put("Something", jsonArray);
}
you can write them back to file like this
//if you write them back to file you will see that 77 and 78 was added to chrome array (single values as you call them)
try(FileWriter fileWriter = new FileWriter("test.json")){
fileWriter.write(jsonObject.toString(5));
}catch (IOException ignore){
}
and after opening test.json file result will be next
{
"win_res": "1366X768",
"layout": "portrait",
"configs": {
"windows 10": {
"chrome": [
"76",
"75"
],
"firefox": [
"67",
"66"
]
},
"macos mojave": {
"chrome": [
"76",
"75",
"77",
"78"
],
"firefox": [
"67",
"66"
]
}
},
"smart_scroll": true,
"defer_time": 5,
"mac_res": "1024x768",
"url": "https://www.apple.com",
"email": true
}
as you see 77 and 78 was appended to "chrome" JSONArray. file will not track order because behind the scenes it is using HashMap.
Try to parse your string to the example Java object. Then call the toString method.
ObjectMapper mapper = newObjectMapper();
String jsonInString = "your string";
//JSON from String to Object
Example yourExample = mapper.readValue(jsonInString, Example.class);
yourExample.toString();
-----------------------------------com.example.Configs.java-----------------------------------
package com.example;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({
"windows 10",
"macos mojave"
})
public class Configs {
#JsonProperty("windows 10")
private Windows10 windows10;
#JsonProperty("macos mojave")
private MacosMojave macosMojave;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
#JsonProperty("windows 10")
public Windows10 getWindows10() {
return windows10;
}
#JsonProperty("windows 10")
public void setWindows10(Windows10 windows10) {
this.windows10 = windows10;
}
#JsonProperty("macos mojave")
public MacosMojave getMacosMojave() {
return macosMojave;
}
#JsonProperty("macos mojave")
public void setMacosMojave(MacosMojave macosMojave) {
this.macosMojave = macosMojave;
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
#Override
public String toString() {
return new ToStringBuilder(this).append("windows10", windows10).append("macosMojave", macosMojave).append("additionalProperties", additionalProperties).toString();
}
#Override
public int hashCode() {
return new HashCodeBuilder().append(windows10).append(additionalProperties).append(macosMojave).toHashCode();
}
#Override
public boolean equals(Object other) {
if (other == this) {
return true;
}
if ((other instanceof Configs) == false) {
return false;
}
Configs rhs = ((Configs) other);
return new EqualsBuilder().append(windows10, rhs.windows10).append(additionalProperties, rhs.additionalProperties).append(macosMojave, rhs.macosMojave).isEquals();
}
}
-----------------------------------com.example.Example.java-----------------------------------
package com.example;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({
"url",
"defer_time",
"email",
"mac_res",
"win_res",
"smart_scroll",
"layout",
"configs"
})
public class Example {
#JsonProperty("url")
private String url;
#JsonProperty("defer_time")
private long deferTime;
#JsonProperty("email")
private boolean email;
#JsonProperty("mac_res")
private String macRes;
#JsonProperty("win_res")
private String winRes;
#JsonProperty("smart_scroll")
private boolean smartScroll;
#JsonProperty("layout")
private String layout;
#JsonProperty("configs")
private Configs configs;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
#JsonProperty("url")
public String getUrl() {
return url;
}
#JsonProperty("url")
public void setUrl(String url) {
this.url = url;
}
#JsonProperty("defer_time")
public long getDeferTime() {
return deferTime;
}
#JsonProperty("defer_time")
public void setDeferTime(long deferTime) {
this.deferTime = deferTime;
}
#JsonProperty("email")
public boolean isEmail() {
return email;
}
#JsonProperty("email")
public void setEmail(boolean email) {
this.email = email;
}
#JsonProperty("mac_res")
public String getMacRes() {
return macRes;
}
#JsonProperty("mac_res")
public void setMacRes(String macRes) {
this.macRes = macRes;
}
#JsonProperty("win_res")
public String getWinRes() {
return winRes;
}
#JsonProperty("win_res")
public void setWinRes(String winRes) {
this.winRes = winRes;
}
#JsonProperty("smart_scroll")
public boolean isSmartScroll() {
return smartScroll;
}
#JsonProperty("smart_scroll")
public void setSmartScroll(boolean smartScroll) {
this.smartScroll = smartScroll;
}
#JsonProperty("layout")
public String getLayout() {
return layout;
}
#JsonProperty("layout")
public void setLayout(String layout) {
this.layout = layout;
}
#JsonProperty("configs")
public Configs getConfigs() {
return configs;
}
#JsonProperty("configs")
public void setConfigs(Configs configs) {
this.configs = configs;
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
#Override
public String toString() {
return new ToStringBuilder(this).append("url", url).append("deferTime", deferTime).append("email", email).append("macRes", macRes).append("winRes", winRes).append("smartScroll", smartScroll).append("layout", layout).append("configs", configs).append("additionalProperties", additionalProperties).toString();
}
#Override
public int hashCode() {
return new HashCodeBuilder().append(configs).append(winRes).append(deferTime).append(email).append(additionalProperties).append(macRes).append(layout).append(smartScroll).append(url).toHashCode();
}
#Override
public boolean equals(Object other) {
if (other == this) {
return true;
}
if ((other instanceof Example) == false) {
return false;
}
Example rhs = ((Example) other);
return new EqualsBuilder().append(configs, rhs.configs).append(winRes, rhs.winRes).append(deferTime, rhs.deferTime).append(email, rhs.email).append(additionalProperties, rhs.additionalProperties).append(macRes, rhs.macRes).append(layout, rhs.layout).append(smartScroll, rhs.smartScroll).append(url, rhs.url).isEquals();
}
}
-----------------------------------com.example.MacosMojave.java-----------------------------------
package com.example;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({
"chrome",
"firefox"
})
public class MacosMojave {
#JsonProperty("chrome")
private List<String> chrome = null;
#JsonProperty("firefox")
private List<String> firefox = null;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
#JsonProperty("chrome")
public List<String> getChrome() {
return chrome;
}
#JsonProperty("chrome")
public void setChrome(List<String> chrome) {
this.chrome = chrome;
}
#JsonProperty("firefox")
public List<String> getFirefox() {
return firefox;
}
#JsonProperty("firefox")
public void setFirefox(List<String> firefox) {
this.firefox = firefox;
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
#Override
public String toString() {
return new ToStringBuilder(this).append("chrome", chrome).append("firefox", firefox).append("additionalProperties", additionalProperties).toString();
}
#Override
public int hashCode() {
return new HashCodeBuilder().append(firefox).append(additionalProperties).append(chrome).toHashCode();
}
#Override
public boolean equals(Object other) {
if (other == this) {
return true;
}
if ((other instanceof MacosMojave) == false) {
return false;
}
MacosMojave rhs = ((MacosMojave) other);
return new EqualsBuilder().append(firefox, rhs.firefox).append(additionalProperties, rhs.additionalProperties).append(chrome, rhs.chrome).isEquals();
}
}
-----------------------------------com.example.Windows10.java-----------------------------------
package com.example;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({
"chrome",
"firefox"
})
public class Windows10 {
#JsonProperty("chrome")
private List<String> chrome = null;
#JsonProperty("firefox")
private List<String> firefox = null;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
#JsonProperty("chrome")
public List<String> getChrome() {
return chrome;
}
#JsonProperty("chrome")
public void setChrome(List<String> chrome) {
this.chrome = chrome;
}
#JsonProperty("firefox")
public List<String> getFirefox() {
return firefox;
}
#JsonProperty("firefox")
public void setFirefox(List<String> firefox) {
this.firefox = firefox;
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
#Override
public String toString() {
return new ToStringBuilder(this).append("chrome", chrome).append("firefox", firefox).append("additionalProperties", additionalProperties).toString();
}
#Override
public int hashCode() {
return new HashCodeBuilder().append(firefox).append(additionalProperties).append(chrome).toHashCode();
}
#Override
public boolean equals(Object other) {
if (other == this) {
return true;
}
if ((other instanceof Windows10) == false) {
return false;
}
Windows10 rhs = ((Windows10) other);
return new EqualsBuilder().append(firefox, rhs.firefox).append(additionalProperties, rhs.additionalProperties).append(chrome, rhs.chrome).isEquals();
}
}
Here is how you could do it with BSON
import java.util.ArrayList;
import org.bson.Document;
Declare all the json objects and arrays you plan to use in your code.
Document root= new Document();
Document rootConfigs = new Document();
Document rootConfigsWindows10 = new Document();
ArrayList rootConfigsWindows10Chrome= new ArrayList();
ArrayList rootConfigsWindows10Firefox= new ArrayList();
Document rootConfigsMacosmojave = new Document();
ArrayList rootConfigsMacosmojaveChrome= new ArrayList();
ArrayList rootConfigsMacosmojaveFirefox= new ArrayList();
Assign out your strings and integers to the correct JSON documents.
root.append("url","https://www.apple.com");
root.append("defer_time",5);
root.append("email",true);
root.append("mac_res","1024x768");
root.append("win_res","1366X768");
root.append("smart_scroll",true);
root.append("layout","portrait");
rootConfigsWindows10Chrome.add("76");
rootConfigsWindows10Chrome.add("75");
rootConfigsWindows10Firefox.add("67");
rootConfigsWindows10Firefox.add("66");
rootConfigsMacosmojaveChrome.add("76");
rootConfigsMacosmojaveChrome.add("75");
rootConfigsMacosmojaveFirefox.add("67");
rootConfigsMacosmojaveFirefox.add("66");
Merge all the jsons together in the right order to form your nested JSON in the ROOT object
if (!rootConfigsWindows10Chrome.isEmpty()){
rootConfigsWindows10.append("chrome",rootConfigsWindows10Chrome);
}
if (!rootConfigsWindows10Firefox.isEmpty()){
rootConfigsWindows10.append("firefox",rootConfigsWindows10Firefox);
}
if (!rootConfigsWindows10.isEmpty()){
rootConfigs.append("windows 10",rootConfigsWindows10);
}
if (!rootConfigsMacosmojaveChrome.isEmpty()){
rootConfigsMacosmojave.append("chrome",rootConfigsMacosmojaveChrome);
}
if (!rootConfigsMacosmojaveFirefox.isEmpty()){
rootConfigsMacosmojave.append("firefox",rootConfigsMacosmojaveFirefox);
}
if (!rootConfigsMacosmojave.isEmpty()){
rootConfigs.append("macos mojave",rootConfigsMacosmojave);
}
if (!rootConfigs.isEmpty()){
root.append("configs",rootConfigs);
}
Output your JSON to see if it worked.
System.out.println(root.toJson());

Mapping json to Object

I am trying to map a json response that looks something like this
{
"0" : "name",
"1" : "school",
"2" : "hobby",
"3" : "bank",
"4" : "games"
}
The json response is dyanamic and can include other fields depending on how its called so i cant use something like
public class InfoWareAPIResponse {
private String name;
private String school;
//getters and setters
}
Please how can i create a class that i can map such json object to??
you can use a java pojo like this.
package com.something;
import com.fasterxml.jackson.annotation.*;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({})
public class InfoUnAwareAPIResponse {
#JsonIgnore
#Valid
private Map<String, Object> additionalProperties = new HashMap();
public InfoUnAwareAPIResponse() {
}
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
public int hashCode() {
return (new HashCodeBuilder()).append(this.additionalProperties).toHashCode();
}
public boolean equals(Object other) {
if (other == this) {
return true;
} else if (!(other instanceof InfoUnAwareAPIResponse)) {
return false;
} else {
InfoUnAwareAPIResponse rhs = (InfoUnAwareAPIResponse) other;
return (new EqualsBuilder()).append(this.additionalProperties, rhs.additionalProperties).isEquals();
}
}
}
And marshel string like this
public static void main(String args[]) throws IOException {
InfoUnAwareAPIResponse in = mapJsonToObject("{\"hello\":\"world\"}", InfoUnAwareAPIResponse.class);
System.out.print("" + in.toString());
}
public static <T> T mapJsonToObject(String input, Class<T> clazz) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
T requestedClass = objectMapper.readValue(input, clazz);
return requestedClass;
}
I ran the above code and it works fine for me.

XML Mapping of POJO to XML using jackson produces duplicate tags

Input Sample:
{
"InventoryDetails" : {
"Inventory" : {
"Details" : {
"Category" : "Fruits",
"Type" : "Perishable"
},
"Properties" : {
"OptField" : [ {
"Name" : "Apple",
"Value" : "Red"
}, {
"Name" : "Orange",
"Value" : "Orange"
}, {
"Name" : "Grapes",
"Value" : "Green"
}
]
}
}
}
}
I am mapping the json to pojo, and trying to convert the pojo to xml using xml mapper.
There is a requirement for making this transformation, without converting json to xml directly, so I have to stick to it, as we have some transformation process before converting to xml
But when i do that, I could see the root element tag is printed twice, Can someone help with me to fix this.
Output
<InventoryDetails>
<InventoryDetails>
<Inventory>
<Details>
<Category>Fruits</Category>
<Type>Perishable</Type>
</Details>
<Properties>
<OptField>
<Name>Apple</Name>
<Value>Red</Value>
</OptField>
<OptField>
<Name>Orange</Name>
<Value>Orange</Value>
</OptField>
<OptField>
<Name>Grapes</Name>
<Value>Green</Value>
</OptField>
</Properties>
</Inventory>
</InventoryDetails>
</InventoryDetails>
POJO 1
package com.inventory;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
#JsonInclude(JsonInclude.Include.NON_NULL)
#Generated("org.jsonschema2pojo")
#JsonPropertyOrder({
"Inventory"
})
public class InventoryDetails {
#JsonProperty("Inventory")
private com.inventory.Inventory Inventory;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
/**
*
* #return
* The Inventory
*/
#JsonProperty("Inventory")
public com.inventory.Inventory getInventory() {
return Inventory;
}
/**
*
* #param Inventory
* The Inventory
*/
#JsonProperty("Inventory")
public void setInventory(com.inventory.Inventory Inventory) {
this.Inventory = Inventory;
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
POJO 2
package com.inventory;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
#JsonInclude(JsonInclude.Include.NON_NULL)
#Generated("org.jsonschema2pojo")
#JsonPropertyOrder({
"Details",
"Properties"
})
public class Inventory {
#JsonProperty("Details")
private com.inventory.Details Details;
#JsonProperty("Properties")
private com.inventory.Properties Properties;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
/**
*
* #return
* The Details
*/
#JsonProperty("Details")
public com.inventory.Details getDetails() {
return Details;
}
/**
*
* #param Details
* The Details
*/
#JsonProperty("Details")
public void setDetails(com.inventory.Details Details) {
this.Details = Details;
}
/**
*
* #return
* The Properties
*/
#JsonProperty("Properties")
public com.inventory.Properties getProperties() {
return Properties;
}
/**
*
* #param Properties
* The Properties
*/
#JsonProperty("Properties")
public void setProperties(com.inventory.Properties Properties) {
this.Properties = Properties;
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
POJO 3
package com.inventory;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
#JsonInclude(JsonInclude.Include.NON_NULL)
#Generated("org.jsonschema2pojo")
#JsonPropertyOrder({
"Category",
"Type"
})
public class Details {
#JsonProperty("Category")
private String Category;
#JsonProperty("Type")
private String Type;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
/**
*
* #return
* The Category
*/
#JsonProperty("Category")
public String getCategory() {
return Category;
}
/**
*
* #param Category
* The Category
*/
#JsonProperty("Category")
public void setCategory(String Category) {
this.Category = Category;
}
/**
*
* #return
* The Type
*/
#JsonProperty("Type")
public String getType() {
return Type;
}
/**
*
* #param Type
* The Type
*/
#JsonProperty("Type")
public void setType(String Type) {
this.Type = Type;
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
POJO 4
package com.inventory;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
#JsonInclude(JsonInclude.Include.NON_NULL)
#Generated("org.jsonschema2pojo")
#JsonPropertyOrder({
"OptField"
})
public class Properties {
#JsonProperty("OptField")
private List<com.inventory.OptField> OptField = new ArrayList<com.inventory.OptField>();
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
/**
*
* #return
* The OptField
*/
#JsonProperty("OptField")
public List<com.inventory.OptField> getOptField() {
return OptField;
}
/**
*
* #param OptField
* The OptField
*/
#JsonProperty("OptField")
public void setOptField(List<com.inventory.OptField> OptField) {
this.OptField = OptField;
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
POJO 5
package com.inventory;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
#JsonInclude(JsonInclude.Include.NON_NULL)
#Generated("org.jsonschema2pojo")
#JsonPropertyOrder({
"Name",
"Value"
})
public class OptField {
#JsonProperty("Name")
private String Name;
#JsonProperty("Value")
private String Value;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
/**
*
* #return
* The Name
*/
#JsonProperty("Name")
public String getName() {
return Name;
}
/**
*
* #param Name
* The Name
*/
#JsonProperty("Name")
public void setName(String Name) {
this.Name = Name;
}
/**
*
* #return
* The Value
*/
#JsonProperty("Value")
public String getValue() {
return Value;
}
/**
*
* #param Value
* The Value
*/
#JsonProperty("Value")
public void setValue(String Value) {
this.Value = Value;
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
Code TO Test
package com.tester;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import org.apache.commons.io.IOUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.inventory.InventoryDetails;
public class Tester {
public static void main(String[] args) {
String jsonStr = "";
try (InputStream inputStream = new FileInputStream(
new File("file.json"))) {
jsonStr = IOUtils.toString(inputStream);
} catch (Exception e) {
System.out.println(e.getMessage());
}
// Map to POJO
ObjectMapper mapper = new ObjectMapper();
InventoryDetails inventoryDetails = null;
try {
inventoryDetails = mapper
.readValue(jsonStr, InventoryDetails.class);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Print XML
ObjectMapper xmlMapper = new XmlMapper();
String request = "";
try {
request = xmlMapper.writeValueAsString(inventoryDetails);
} catch (JsonProcessingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(request);
}
}
As from here by default simple class name is used as root element.
To overcome this remove enclosing object from input JSON:
{
"Inventory" : {
"Details" : {
"Category" : "Fruits",
"Type" : "Perishable"
},
"Properties" : {
"OptField" : [ {
"Name" : "Apple",
"Value" : "Red"
}, {
"Name" : "Orange",
"Value" : "Orange"
}, {
"Name" : "Grapes",
"Value" : "Green"
}
]
}
}
}

JAXB - How to create the XML element with attributes from Map?

I need something like this -
<Token>
<HighLevel info-1="" info-2=""/>
<LowLevel>
<LowLevel info-key="" info-value=""/>
<LowLevel info-key="" info-value=""/>
....
</LowLevel>
</Token >
I've the Map for LowLevel element, whose entries I want to populate like above XML.
What could be the way to encapsulate/bind this using JAXB?
You could use a custom adapter for this. Example
//Token.java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
#XmlRootElement
class LowLevelToken {
#XmlAttribute(name = "info-key")
public String key;
#XmlAttribute(name = "info-value")
public String value;
private LowLevelToken() {}
public LowLevelToken(String key, String value) {
this.key = key;
this.value = value;
}
}
#XmlRootElement
class HighLevelToken {
#XmlAttribute(name = "info-1")
public String info1;
#XmlAttribute(name = "info-2")
public String info2;
private HighLevelToken() {}
public HighLevelToken(String info1, String info2) {
this.info1 = info1;
this.info2 = info2;
}
}
class TokenWrapper {
#XmlElement(name="LowLevel")
public List<LowLevelToken> tokens = new ArrayList<LowLevelToken>();
}
class TokenAdapter extends XmlAdapter<TokenWrapper, Map<String, String>> {
#Override
public TokenWrapper marshal(Map<String, String> lowlevelTokens)
throws Exception {
TokenWrapper wrapper = new TokenWrapper();
List<LowLevelToken> elements = new ArrayList<LowLevelToken>();
for (Map.Entry<String, String> property : lowlevelTokens.entrySet()) {
elements.add(new LowLevelToken(property.getKey(), property.getValue()));
}
wrapper.tokens = elements;
return wrapper;
}
#Override
public Map<String, String> unmarshal(TokenWrapper tokenWrapper) throws Exception {
Map<String, String> tokens = null;
if(tokenWrapper != null && tokenWrapper.tokens != null && !tokenWrapper.tokens.isEmpty()){
tokens = new HashMap<String, String>();
for(LowLevelToken token : tokenWrapper.tokens){
tokens.put(token.key, token.value);
}
}
return tokens;
}
}
#XmlRootElement(name = "Token")
public class Token {
HighLevelToken highLevel;
Map<String, String> lowLevel;
public HighLevelToken getHighLevel() {
return highLevel;
}
#XmlElement(name = "HighLevel")
public void setHighLevel(HighLevelToken highLevel) {
this.highLevel = highLevel;
}
public Map<String, String> getLowLevel() {
return lowLevel;
}
#XmlElement(name = "LowLevel")
#XmlJavaTypeAdapter(TokenAdapter.class)
public void setLowLevel(Map<String, String> lowLevel) {
this.lowLevel = lowLevel;
}
}
A sample program
import java.util.HashMap;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
public class JAXBExample {
public static void main(String[] args) {
Token token = new Token();
token.setHighLevel(new HighLevelToken("1", "2"));
token.setLowLevel(new HashMap<String, String>() {{ put("LK1", "LV1"); put("LK2", "LV2"); put("LK2", "LV2"); }});
try {
JAXBContext jaxbContext = JAXBContext.newInstance(Token.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(token, System.out);
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
This generates
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Token>
<HighLevel info-1="1" info-2="2"/>
<LowLevel>
<LowLevel info-key="LK2" info-value="LV2"/>
<LowLevel info-key="LK1" info-value="LV1"/>
</LowLevel>
</Token>

Categories