我想在java中使用jackson时能够为序列化和反序列化的json对象设置不同的名称。 更具体一点:我从一个在其JSON属性上使用一个名称标准的API获取数据,但是我的端点使用不同的一个,因为我在这种情况下只想传递数据我希望能够将属性转换为我的名称标准。
我在这里已经阅读了类似的问题,但我似乎无法让它发挥作用。
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
。
有没有人做过类似的事情,看看我尝试过的是什么问题?
答案 0 :(得分:2)
你走在正确的轨道上。以下是使用测试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"}
}
}