[英]Different serialization/deserialization names with java jackson
我希望在Java中使用jackson時能夠為序列化和反序列化的json對象使用不同的名稱。 更具體一點:我正在從API中獲取數據,該API在其JSON屬性上使用一種名稱標准,但是我的端點使用了另一種名稱,因此在這種情況下,我只想傳遞數據能夠將屬性轉換為我的名字標准。
我在這里讀過類似的問題,但我似乎無法使其正常運行。
private String defaultReference;
@JsonProperty(value = "default_reference", access = JsonProperty.Access.WRITE_ONLY)
public void setDefaultReference(String defaultReference)
{
this.defaultReference = defaultReference;
}
@JsonProperty(value = "defaultReference", access = JsonProperty.Access.READ_ONLY)
public String getDefaultReference()
{
return defaultReference;
}
那是我最近的嘗試。 問題是它總是返回null,所以不使用setter。
我也嘗試過:
@JsonProperty(value = "default_reference", access = JsonProperty.Access.WRITE_ONLY)
private String defaultReference;
@JsonProperty(value = "defaultReference", access = JsonProperty.Access.READ_ONLY)
public String getDefaultReference()
{
return defaultReference;
}
這類作品。 它可以反序列化default_reference
。 問題是在JSON響應中,我同時獲得了default_reference
和defaultReference
。 最好我只會得到defaultReference
。
有沒有人做過類似的事情,看看我嘗試過的地方出了什么問題?
您走在正確的軌道上。 這是使用測試JSON文檔的示例。
public static class MyClass {
private String defaultReference;
@JsonProperty(value = "default_reference")
public void setDefaultReference(String defaultReference) {
this.defaultReference = defaultReference;
}
@JsonProperty(value = "defaultReference")
public String getDefaultReference() {
return defaultReference;
}
public static void main(String[] args) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
MyClass instance = objectMapper.readValue("{\"default_reference\": \"value\"}", MyClass.class);
objectMapper.writeValue(System.out, instance);
// Output: {"defaultReference":"value"}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.