我必须创建一个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);

最佳答案

获取以下json字符串

 { "downlinkData" : "deadbeefcafebabe"}


创建json对象(库:java-json.jar)

 JSONObject obj = new JSONObject();


将上面的json字符串放入json对象。

 obj.put("333ee", jsonString);


将创建以下json字符串

{

"333ee" : { "downlinkData" : "deadbeefcafebabe"}
}


我希望这能帮到您。 :-)

10-05 21:10
查看更多