我必须创建一个REST响应。数据采用json格式,必须按以下结构构建:
{
"device_id" : { "downlinkData" : "deadbeefcafebabe"}
}
“device_id”必须替换为DeviceId,例如:
{
"333ee" : { "downlinkData" : "deadbeefcafebabe"}
}
或
{
"9886y" : { "downlinkData" : "deadbeefcafebabe"}
}
我使用了http://www.jsonschema2pojo.org/,这就是结果:
@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);
}
}
和
@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);
}
}
但基于此POJO,我无法设置deviceID:
DownlinkCallbackResponse downlinkCallbackResponse = new DownlinkCallbackResponse ();
DeviceId deviceId = new DeviceId();
deviceId.setDownlinkData(data);
downlinkCallbackResponse.setDeviceId(deviceId);
return new ResponseEntity<>(downlinkCallbackResponse, HttpStatus.OK);
答案 0 :(得分:2)
获取以下json字符串
{ "downlinkData" : "deadbeefcafebabe"}
创建json对象(Lib:java-json.jar)
JSONObject obj = new JSONObject();
将json字符串放在json对象上。
obj.put("333ee", jsonString);
将创建以下json字符串
{
"333ee" : { "downlinkData" : "deadbeefcafebabe"}
}
我希望这会对你有所帮助。 : - )