JAVA json 方案2 POJO

JAVA json schema 2 POJO

我必须创建一个 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,我无法设置设备 ID:

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"}
}

希望对您有所帮助。 :-)