2017-05-31 47 views
1

我必須創建一個REST響應。數據被JSON格式,並且必須被構造爲執行以下操作:JAVA json模式2 POJO

{ 
    "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); 
+0

「我無法設置設備ID」你是什麼意思? – 2017-05-31 20:55:18

+0

POJO中沒有setter來取代device_id的真實ID –

+0

例如https://stackoverflow.com/a/39923458/180100例如 – 2017-06-01 05:11:46

回答

2

得到以下JSON字符串

{ "downlinkData" : "deadbeefcafebabe"} 

創建JSON對象(庫:Java的JSON .jar)

JSONObject obj = new JSONObject(); 

將上面的json字符串放到json對象中。

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

,將創建下列JSON字符串

{ 

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

我希望這會幫助你。 :-)