I have to create a REST response. The data is json formatted, and must be structured as the following :
{
"device_id" : { "downlinkData" : "deadbeefcafebabe"}
}
"device_id" has to replaced for the DeviceId, for instance:
{
"333ee" : { "downlinkData" : "deadbeefcafebabe"}
}
or
{
"9886y" : { "downlinkData" : "deadbeefcafebabe"}
}
I used http://www.jsonschema2pojo.org/ and this is the result:
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({
"device_id"
})
public class DownlinkCallbackResponse {
#JsonProperty("device_id")
private DeviceId deviceId;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
#JsonProperty("device_id")
public DeviceId getDeviceId() {
return deviceId;
}
#JsonProperty("device_id")
public void setDeviceId(DeviceId deviceId) {
this.deviceId = deviceId;
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
and
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({
"downlinkData"
})
public class DeviceId {
#JsonProperty("downlinkData")
private String downlinkData;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
#JsonProperty("downlinkData")
public String getDownlinkData() {
return downlinkData;
}
#JsonProperty("downlinkData")
public void setDownlinkData(String downlinkData) {
this.downlinkData = downlinkData;
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
But based on this POJOs I can't set the deviceID:
DownlinkCallbackResponse downlinkCallbackResponse = new DownlinkCallbackResponse ();
DeviceId deviceId = new DeviceId();
deviceId.setDownlinkData(data);
downlinkCallbackResponse.setDeviceId(deviceId);
return new ResponseEntity<>(downlinkCallbackResponse, HttpStatus.OK);
get following json string
{ "downlinkData" : "deadbeefcafebabe"}
create json object ( Lib : java-json.jar )
JSONObject obj = new JSONObject();
put above json string into json object.
obj.put("333ee", jsonString);
that will create following json string
{
"333ee" : { "downlinkData" : "deadbeefcafebabe"}
}
I hope this will help you. :-)
Related
I want to create one API which format will be like below.
{
"jsonObject": {
//some json object
},
"key": "SampleKey",
"jsonDataKey": "SampleDataKey"
}
for this I have created the RequestBody class as below.
public class ParentJsonInfo {
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
private String key;
public JsonObject getJsonData() {
return jsonData;
}
public void setJsonData(JsonObject jsonData) {
this.jsonData = jsonData;
}
private JsonObject jsonData;
public String getJsonDataKey() {
return jsonDataKey;
}
public void setJsonDataKey(String jsonDataKey) {
this.jsonDataKey = jsonDataKey;
}
private String jsonDataKey;
}
but unfortunately I am not getting any data inside the json object of my class. M I doing anything wrong. please guide me to how should i access the data inside that object.
Here is the controller method code.
#RequestMapping(value = "/postNews", method = RequestMethod.POST)
public Greeting greeting(#RequestBody ParentJsonInfo parentJsonInfo) {
Jsonobject jsonObject= parentJsonInfo.getjsonObject();
}
The problem you are having is that you are trying to deserialize jsonObject which is from your json, but your field is called jsonData.
As #Mushtu mentioned, you need to rename that field.
Here is your ParentJsonInfo with a few adjustments:
moving the fields to the top (it is a good practice to group fields and methods separately)
renamed your field from jsonData to jsonObject
ParentJsonInfo:
public class ParentJsonInfo {
private String key;
private JsonObject jsonObject;
private String jsonDataKey;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public JsonObject getJsonObject() {
return jsonObject;
}
public void setJsonObject(JsonObject jsonObject) {
this.jsonObject = jsonObject;
}
public String getJsonDataKey() {
return jsonDataKey;
}
public void setJsonDataKey(String jsonDataKey) {
this.jsonDataKey = jsonDataKey;
}
}
JsonObject:
public class JsonObject {
private Map<String, Object> other = new HashMap<>();
#JsonAnyGetter
public Map<String, Object> getProperties() {
return other;
}
#JsonAnySetter
public void set(String name, String value) {
other.put(name, value);
}
}
u can modify like this
public Greeting greeting(#RequestBody String parentJsonInfo) {
// parse string to jsonobject
}
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.
while hitting below method only key of map which is 'name' is coming in response .....
why value of map which is ArrayList is not coming in response
endpoint of mehtod is as below
public LoginResponse LoginUserJSON(LoginRequestVO requestVOLogin)
{
LoginResponse lr = new LoginResponse();
Map<String, ArrayList<String>> mapObj = new
HashMap<String,ArrayList<String>>();
ArrayList<String> loginRequestVOs = new ArrayList<>();
lr.setStatus("Done");
loginRequestVOs.add("parth1");
loginRequestVOs.add("parth2");
mapObj.put("name", loginRequestVOs);
lr.setRequestData(mapObj);
System.out.println(mapObj);
return lr;
}
responsevo is as below
#XmlRootElement(name= "Response")
#XmlAccessorType(XmlAccessType.FIELD)
public class LoginResponse
{
#XmlElement(name = "status")
String status;
#XmlElement(name = "requestData")
private Map<String, ArrayList<String>> requestData;
public String getStatus()
{
return status;
}
public void setStatus(String status)
{
this.status = status;
}
public Map<String, ArrayList<String>> getRequestData()
{
return requestData;
}
public void setRequestData(Map<String, ArrayList<String>> requestData)
{
this.requestData = requestData;
}
}
you can try out the stream api if you are using java 8
Map<String, ArrayList<String>> mapObj = new HashMap<>();
mapObj.entrySet()
.stream()
.map(entry -> String.format("[key: %s, value: %s]", entry.getKey(), Arrays.toString(entry.getValue().toArray())))
.forEach(System.out::println)
;
just a quick question around Lambda Expressions. I have the following text:
{"hosts":[{"disks":[{"path":"/","space_used":0.608}],"hostname":"host1"},{"disks":[{"path":"/","space_used":0.79},{"path":"/opt","space_used":0.999}],"hostname":"host2"},{"disks":[{"path":"/","space_used":0.107}],"hostname":"host3"}]}
Which I'd like to format the above to each line reading:
{"hostname": "host1", "disks":["Path '/' had utilised 60.8%"]}
{"hostname": "host2", "disks":["Path '/' had utilised 79%", "Path '/opt' had utilised 99.9%"]}
{"hostname": "host3", "disks":["Path '/' had utilised 10.7%"]}
I've tried a few permutations around .stream().map() and then .collect() but somehow I came up short in getting to the output I needed. Any help is much appreciated and apologies if the question is rather n00bish. Thanks.
You could use the Jackson 2 Library to convert your JSON-String to Java objects.
In your concrete case you could e.g. create the following classes:
Disk.java
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({"path", "space_used"})
public class Disk implements Serializable {
private final static long serialVersionUID = -6127352847480270783L;
#JsonProperty("path")
private String path;
#JsonProperty("space_used")
private Double spaceUsed;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
#JsonProperty("path")
public String getPath() {
return path;
}
#JsonProperty("path")
public void setPath(String path) {
this.path = path;
}
#JsonProperty("space_used")
public Double getSpaceUsed() {
return spaceUsed;
}
#JsonProperty("space_used")
public void setSpaceUsed(Double spaceUsed) {
this.spaceUsed = spaceUsed;
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
Host.java
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({"disks", "hostname"})
public class Host implements Serializable {
private final static long serialVersionUID = -1972892789688333505L;
#JsonProperty("disks")
private List<Disk> disks = null;
#JsonProperty("hostname")
private String hostname;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
#JsonProperty("disks")
public List<Disk> getDisks() {
return disks;
}
#JsonProperty("disks")
public void setDisks(List<Disk> disks) {
this.disks = disks;
}
#JsonProperty("hostname")
public String getHostname() {
return hostname;
}
#JsonProperty("hostname")
public void setHostname(String hostname) {
this.hostname = hostname;
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
HostContainer.java
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({"hosts"})
public class HostContainer implements Serializable {
private final static long serialVersionUID = 7917934809738573749L;
#JsonProperty("hosts")
private List<Host> hosts = null;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
#JsonProperty("hosts")
public List<Host> getHosts() {
return hosts;
}
#JsonProperty("hosts")
public void setHosts(List<Host> hosts) {
this.hosts = hosts;
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
Usage:
public void parseMessage() throws IOException {
String msg = "{\"hosts\":[{\"disks\":[{\"path\":\"/\",\"space_used\":0.608}]," +
"\"hostname\":\"host1\"},{\"disks\":[{\"path\":\"/\",\"space_used\":0.79}," +
"{\"path\":\"/opt\",\"space_used\":0.999}],\"hostname\":\"host2\"}," +
"{\"disks\":[{\"path\":\"/\",\"space_used\":0.107}],\"hostname\":\"host3\"}]}";
ObjectMapper mapper = new ObjectMapper();
// This object will contain all the information you need, access it using e.g. getHosts();
HostContainer hostContainer = mapper.readValue(msg, HostContainer.class);
}
I am trying to get java object from dynamic JSON.
One Important point these given classes are from third party API.
#JsonTypeInfo(
use = Id.NAME,
include = As.PROPERTY,
property = "nodeType"
)
#JsonSubTypes({ #Type(
name = "Filter",
value = Filter.class
), #Type(
name = "Criterion",
value = Criterion.class
)})
public abstract class Node {
public Node() {
}
#JsonIgnore
public EvaluationResult evaluate(Map<UUID, List<AnswerValue>> answers) {
Evaluator evaluator = new Evaluator();
return evaluator.evaluateAdvancedLogic(this, answers);
}
}
Filter.java
#JsonInclude(Include.NON_NULL)
#JsonPropertyOrder({"evaluationType", "filters"})
public class Filter extends Node {
#JsonProperty("evaluationType")
private EvaluationType evaluationType;
#NotNull
#JsonProperty("filters")
#Valid
private List<Node> filters = new ArrayList();
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap();
public Filter() {
}
#JsonProperty("evaluationType")
public EvaluationType getEvaluationType() {
return this.evaluationType;
}
#JsonProperty("evaluationType")
public void setEvaluationType(EvaluationType evaluationType) {
this.evaluationType = evaluationType;
}
#JsonProperty("filters")
public List<Node> getFilters() {
return this.filters;
}
#JsonProperty("filters")
public void setFilters(List<Node> filters) {
this.filters = filters;
}
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
}
Criterion.java
#JsonInclude(Include.NON_NULL)
#JsonPropertyOrder({"fieldSourceType", "fieldCategoryName", "sequenceNumber", "fieldName", "values", "operator", "fieldId"})
public class Criterion extends Node {
#JsonProperty("fieldSourceType")
private FieldSourceType fieldSourceType;
#JsonProperty("fieldCategoryName")
private String fieldCategoryName;
#NotNull
#JsonProperty("sequenceNumber")
private Long sequenceNumber;
#JsonProperty("fieldName")
private String fieldName;
#JsonProperty("values")
#Valid
private List<String> values = new ArrayList();
#JsonProperty("operator")
#Valid
private Operator operator;
#NotNull
#JsonProperty("fieldId")
private UUID fieldId;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap();
public Criterion() {
}
#JsonProperty("fieldSourceType")
public FieldSourceType getFieldSourceType() {
return this.fieldSourceType;
}
#JsonProperty("fieldSourceType")
public void setFieldSourceType(FieldSourceType fieldSourceType) {
this.fieldSourceType = fieldSourceType;
}
#JsonProperty("fieldCategoryName")
public String getFieldCategoryName() {
return this.fieldCategoryName;
}
#JsonProperty("fieldCategoryName")
public void setFieldCategoryName(String fieldCategoryName) {
this.fieldCategoryName = fieldCategoryName;
}
#JsonProperty("sequenceNumber")
public Long getSequenceNumber() {
return this.sequenceNumber;
}
#JsonProperty("sequenceNumber")
public void setSequenceNumber(Long sequenceNumber) {
this.sequenceNumber = sequenceNumber;
}
#JsonProperty("fieldName")
public String getFieldName() {
return this.fieldName;
}
#JsonProperty("fieldName")
public void setFieldName(String fieldName) {
this.fieldName = fieldName;
}
#JsonProperty("values")
public List<String> getValues() {
return this.values;
}
#JsonProperty("values")
public void setValues(List<String> values) {
this.values = values;
}
#JsonProperty("operator")
public Operator getOperator() {
return this.operator;
}
#JsonProperty("operator")
public void setOperator(Operator operator) {
this.operator = operator;
}
#JsonProperty("fieldId")
public UUID getFieldId() {
return this.fieldId;
}
#JsonProperty("fieldId")
public void setFieldId(UUID fieldId) {
this.fieldId = fieldId;
}
}
The json used to conversion is this.
{
"evaluationType":"AND",
"nodeType":"Criterion",
"Criterion":[
{
"fieldName":"sdada",
"values":"sdad",
"operator":{
"operatorType":"Equals"
}
},
{
"nodeType":"Criterion",
"fieldName":"dasa",
"values":"das",
"operator":{
"operatorType":"Equals"
}
},
{
"nodeType":"Criterion",
"fieldName":"dada",
"values":"dads",
"operator":{
"operatorType":"Equals"
}
}
]
}
The problem is that deserialization of this JSON fails with following error:
{
"message": "Class com.cvent.logic.model.Criterion is not assignable to com.cvent.logic.model.Filter"
}
The first part of the JSON is wrong
{
"evaluationType":"AND",
"nodeType":"Criterion",
"Criterion":[
It says that the type is Criterion but it has evaluationType from Filter.
Also, probably "Criterion" : [ should be "filters" : [