Need to convert below JSON Object to String JAVA - 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());

Related

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.

com.google.gson.JsonSyntaxException:Expected STRING but was BEGIN_ARRAY

Kindly help me to get the subnodes list inside bom attributes
JSON file
[
{
"subConfigId":"bac",
"totalPrice":"634.00",
"bom":{
"ucid":"ucid",
"type":"RootNode",
"attributes":{
"visible":true,
"price_status":"SUCCESS"
},
"subnodes":[
{
"description":"Enterprise Shock Rack",
"ucid":"ucid"
},
{
"description":"SVC",
"ucid":"ucid"
}
]
},
"breakdown":{
"SV":550.0,
"HW":6084.0
},
"currency":"USD"
}
]
GsonNodes.java
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
public class GsonNodes {
public static void main(String[] args) throws IOException {
try{
JsonElement je = new JsonParser().parse(new FileReader(
"C:/Desktop/json.txt"));
JsonArray ja = je.getAsJsonArray();
Iterator itr = ja.iterator();
while(itr.hasNext()){
JsonElement je1 = (JsonElement) itr.next();
Gson gson = new Gson();
Details details = gson.fromJson(je1, Details.class);
System.out.println(details.getSubConfigId());
System.out.println(details.getCurrency());
System.out.println(details.getBreakdown());
System.out.println(details.getTotalPrice());
System.out.println(details.getBom().getUcid());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Details.java POJO
import java.io.Serializable;
import java.util.Map;
public class Details implements Serializable{
private String subConfigId;
private String totalPrice;
private Bom bom;
private String currency;
private Map<String, String> breakdown;
public String getSubConfigId() {
return subConfigId;
}
public void setSubConfigId(String subConfigId) {
this.subConfigId = subConfigId;
}
public String getTotalPrice() {
return totalPrice;
}
public void setTotalPrice(String totalPrice) {
this.totalPrice = totalPrice;
}
public Bom getBom() {
return bom;
}
public void setBom(Bom bom) {
this.bom = bom;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
public Map<String, String> getBreakdown() {
return breakdown;
}
public void setBreakdown(Map<String, String> breakdown) {
this.breakdown = breakdown;
}
}
Bom.java
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class Bom implements Serializable{
private String ucid;
private String type;
private Map<String, String> attributes;
private List<Subnodes> subnodes = new ArrayList<Subnodes>();
public String getUcid() {
return ucid;
}
public void setUcid(String ucid) {
this.ucid = ucid;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Map<String, String> getAttributes() {
return attributes;
}
public void setAttributes(Map<String, String> attributes) {
this.attributes = attributes;
}
#Override
public String toString(){
return getUcid() + ", "+getType()+", "+getAttributes();
}
}
Subnodes.java
import java.io.Serializable;
import java.util.Map;
public class Subnodes implements Serializable{
private String description;
private String ucid;
private Map<String, String> attributes;
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getUcid() {
return ucid;
}
public void setUcid(String ucid) {
this.ucid = ucid;
}
public Map<String, String> getAttributes() {
return attributes;
}
public void setAttributes(Map<String, String> attributes) {
this.attributes = attributes;
}
}
I am getting an error , when i try to get the "subnodes"
I added the following code in the class
private List<Subnodes> subnodes = new ArrayList<Subnodes>();
then i am getting the error "Expected STRING but was BEGIN_ARRAY"
kindly help me that how can i get the "subnodes" list
In Bom.java
Please add a getter/setter method for :
private List<Subnodes> subnodes = new ArrayList<Subnodes>();
public List<Subnodes> getSubnodes() {
return subnodes;
}
public void setSubnodes(List<Subnodes> subnodes) {
this.subnodes = subnodes;
}
i have tried as below .. this is working fine.
package com.brp.mvc.util;
import java.io.IOException;
import java.util.Iterator;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
public class GsonNodes {
public static void main(String[] args) throws IOException {
try {
JsonElement je = new JsonParser().parse("[{\"subConfigId\":\"bac\",\"totalPrice\":\"634.00\",\"bom\":{\"ucid\":\"ucid\",\"type\":\"RootNode\",\"attributes\":{\"visible\":true,\"price_status\":\"SUCCESS\"},\"subnodes\":[{\"description\":\"Enterprise Shock Rack\",\"ucid\":\"ucid\"},{\"description\":\"SVC\",\"ucid\":\"ucid\"}]},\"breakdown\":{\"SV\":550.0,\"HW\":6084.0},\"currency\":\"USD\"}]");
JsonArray ja = je.getAsJsonArray();
Iterator itr = ja.iterator();
while (itr.hasNext()) {
JsonElement je1 = (JsonElement) itr.next();
Gson gson = new Gson();
Details details = gson.fromJson(je1, Details.class);
System.out.println(details.getSubConfigId());
System.out.println(details.getCurrency());
System.out.println(details.getBreakdown());
System.out.println(details.getTotalPrice());
System.out.println(details.getBom().getUcid());
System.out.println(details.getBom().getSubnodes().get(0).getDescription());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
i have added one method to convert json into string as below :
public static String readFile(String filename) {
String result = "";
try {
BufferedReader br = new BufferedReader(new FileReader(filename));
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
line = br.readLine();
}
result = sb.toString();
} catch(Exception e) {
e.printStackTrace();
}
return result;
}
and use this method like below :
JsonElement je = new JsonParser().parse(readFile("C:/Desktop/json.txt"));

Mapping this json to java object (pojo)

I have to map a json which would look like this, it's basicly an object, which can contain the same object again as a child, then that one can also contain the same object again. How would i be able to map this to java pojo's?
This is the json:
{
"group": [
{
"name": "Beheerders",
"desc": "Beheerders",
"children" : [
"group" : [
{
"name": "Beheerders",
"desc": "Beheerders"
},
{
"name": "Beheerders",
"desc": "Beheerders"
},
{
"name": "Beheerders",
"desc": "Beheerders"
"children": [
"group" : [
{
"name": "Beheerders",
"desc": "Beheerders"
},
{
"name": "Beheerders",
"desc": "Beheerders"
}
}
}
]
}
And i have these 4 pojo's:
Group.java
private String name;
private String desc;
private Children children;
//getters & Setters & toString
GroupList.java
private ArrayList<Group> group;
public void setGroup(ArrayList<Group> group) {
this.group = group;
}
public ArrayList<Group> getGroup() {
return this.group;
}
Children.java
private ArrayList<ChildrenGroup> group;
public ArrayList<ChildrenGroup> getGroup() {
return this.group;
}
public void setGroup(ArrayList<ChildrenGroup> group) {
this.group = group;
}
childrengroup.java
private String name;
private String desc;
private Children Children;
//Getters & Setters & toString
This is not working for me, i always get this error:
com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token
Your JSON is not valid and your objects aren't correctly using object vs List. Please validate your example JSON. "children" : [ "group" : [ is invalid.
Your errors are occurring because it is encountering [ when your java objects are specifying {.
You can remove Children and ChildrenGroup and just nest GroupList inside Group as well.
You can use online tools like jsonschema2pojo to generate POJO from your JSON.
If I'm understanding correctly you are trying to convert smth like the following:
{
"g":[
{
"a":"1",
"c":"2"
},
{
"a":"2",
"c":"3",
"d":[
{
"g":[
{"a":"3",
"c":"4"},
{"a":"5",
"c":"6"}
]
}
]
}
]
}
The output for this one will be:
-----------------------------------com.example.D.java-----------------------------------
package com.example;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class D {
private List<G_> g = null;
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
public List<G_> getG() {
return g;
}
public void setG(List<G_> g) {
this.g = g;
}
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
-----------------------------------com.example.Example.java-----------------------------------
package com.example;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Example {
private List<G> g = null;
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
public List<G> getG() {
return g;
}
public void setG(List<G> g) {
this.g = g;
}
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
-----------------------------------com.example.G.java-----------------------------------
package com.example;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class G {
private String a;
private String c;
private List<D> d = null;
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
public String getA() {
return a;
}
public void setA(String a) {
this.a = a;
}
public String getC() {
return c;
}
public void setC(String c) {
this.c = c;
}
public List<D> getD() {
return d;
}
public void setD(List<D> d) {
this.d = d;
}
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
-----------------------------------com.example.G_.java-----------------------------------
package com.example;
import java.util.HashMap;
import java.util.Map;
public class G_ {
private String a;
private String c;
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
public String getA() {
return a;
}
public void setA(String a) {
this.a = a;
}
public String getC() {
return c;
}
public void setC(String c) {
this.c = c;
}
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}

Reading a json using jackson

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);
}
}

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