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());
I am currently using the jackson gwt library and I was wondering how I can access values that are nested within a json string. My current setup code looks like this:
public static interface PremiumMapper extends ObjectMapper<Premium> {}
public static class Premium {
public float getFaceAmount() {
return faceAmount;
}
public void setFaceAmount(float faceAmount) {
this.faceAmount = faceAmount;
}
public float getStart() {
return start;
}
public void setStart(float start) {
this.start = start;
}
public float getEnd() {
return end;
}
public void setEnd(float end) {
this.end = end;
}
public float start;
public float end;
public float faceAmount;
}
while my access code looks like this:
String json = "{\"errorCode\":\"validation.failed\",\"statusCode\":400,\"details\":[{\"code\":\"targetPremium.monthlyPremiumsCents.outOfBounds\",\"validChoices\":[{\"start\":9450,\"end\":125280}]}]}";
PremiumMapper mapper = GWT.create( PremiumMapper.class );
Premium premium = mapper.read( json );
System.out.println("VALUES OUTPUTTED: " + premium.getStart());
How am I able to get the start value within the json string?
Try This as your Premium class:
-----------------------------------com.example.Premium.java-----------------------------------
package com.example;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Premium {
private String errorCode;
private Integer statusCode;
private List<Detail> details = null;
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
public String getErrorCode() {
return errorCode;
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
public Integer getStatusCode() {
return statusCode;
}
public void setStatusCode(Integer statusCode) {
this.statusCode = statusCode;
}
public List<Detail> getDetails() {
return details;
}
public void setDetails(List<Detail> details) {
this.details = details;
}
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
-----------------------------------com.example.Detail.java-----------------------------------
package com.example;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Detail {
private String code;
private List<ValidChoice> validChoices = null;
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public List<ValidChoice> getValidChoices() {
return validChoices;
}
public void setValidChoices(List<ValidChoice> validChoices) {
this.validChoices = validChoices;
}
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
-----------------------------------com.example.ValidChoice.java-----------------------------------
package com.example;
import java.util.HashMap;
import java.util.Map;
public class ValidChoice {
private Integer start;
private Integer end;
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
public Integer getStart() {
return start;
}
public void setStart(Integer start) {
this.start = start;
}
public Integer getEnd() {
return end;
}
public void setEnd(Integer end) {
this.end = end;
}
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
And get start value like this: premium.getDetails().get(0).getValidChoices(0).getStart()
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.
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);
}
}
I have to make a Json which will form a tree like structure.I have written a java code that is forming a structure like that but it does not satisfy the purpose.Here where i have done so far..This is my java class..
import com.google.gson.FieldNamingStrategy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class GsonProgram {
public static void main(String... args) throws Exception {
String arr[] = {"Culture", "Salary", "Work", "Effort"};
EntryListContainer entryListContainer = new EntryListContainer();
List<Entry> entryList1 = new ArrayList<>();
for (int i = 0; i < arr.length; i++) {
Entry entry1 = new Entry();
Entry entry2 = new Entry();
entry1.setChildren(arr[i]);
entryList1.add(entry1);
entryList2.add(entry2);
entryListContainer.setEntryList1(entryList1);
entryListContainer.setEntryList1(entryList2);
/*Root node this will collapse and get back to Original position on click*/
entryListContainer.setName("Employee");
entryListContainer.setName("manager");
}
Map<String, String> mapping = new HashMap<>();
mapping.put("entryList1", "name");
mapping.put("entryList2", "name");
Gson gson = new GsonBuilder().serializeNulls().setFieldNamingStrategy(new DynamicFieldNamingStrategy(mapping)).create();
System.out.println(gson.toJson(entryListContainer));
}
}
class DynamicFieldNamingStrategy implements FieldNamingStrategy {
private Map<String, String> mapping;
public DynamicFieldNamingStrategy(Map<String, String> mapping) {
this.mapping = mapping;
}
#Override
public String translateName(Field field) {
String newName = mapping.get(field.getName());
if (newName != null) {
return newName;
}
return field.getName();
}
}
class EntryListContainer {
private List<Entry> entryList1;
public void setEntryList1(List<Entry> entryList1) {
this.entryList1 = entryList1;
}
public List<Entry> getEntryList1() {
return entryList1;
}
}
class Entry {
private String name;
public String getChildren() {
return name;
}
public void setChildren(String name) {
this.name = name;
}
}
and this is the generated json
{
"name":[{
"name":"Salary"
},{
"name":"Salary"
},{
"name":"Work"
},{
"name":"Doller"
}]
}
But i want this structure...
{
"name":"Employee",
"children":[{
"name":"Salary"
},{
"name":"Salary"
},{
"name":"Work"
},{
"name":"Doller"
}]
}
I need this format of json.somebody please help....
The pseudo class structure should be:
class DynamicFieldNamingStrategy{
private String name;
private List<Entry> children;
}
GsonProgram
public class GsonProgram {
public static void main(String... args) throws Exception {
Entry entry1 = new Entry();
entry1.setChildren("Salary");
Entry entry2 = new Entry();
entry2.setChildren("Salary");
Entry entry3 = new Entry();
entry3.setChildren("Work");
Entry entry4 = new Entry();
entry4.setChildren("Doller");
EntryListContainer entryListContainer = new EntryListContainer();
ArrayList<Entry> entryList1 = new ArrayList<Entry>();
entryList1.add(entry1);
entryList1.add(entry2);
entryList1.add(entry3);
entryList1.add(entry4);
entryListContainer.setEntryList1(entryList1);
entryListContainer.setName("Employee");
Map<String, String> mapping = new HashMap<String, String>();
mapping.put("entryList1", "name");
Gson gson = new GsonBuilder().serializeNulls().setFieldNamingStrategy(new DynamicFieldNamingStrategy(mapping)).create();
System.out.println(gson.toJson(entryListContainer));
}
}
EntryListContainer
class EntryListContainer {
private List<Entry> children;
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setEntryList1(List<Entry> entryList1) {
this.children = entryList1;
}
public List<Entry> getEntryList1() {
return children;
}
}
Output:
{
"children": [
{
"name": "Salary"
},
{
"name": "Salary"
},
{
"name": "Work"
},
{
"name": "Doller"
}
],
"name": "Employee"
}