简体   繁体   English

使用Java Jackson的不同序列化/反序列化名称

[英]Different serialization/deserialization names with java jackson

I want to be able to have different names for serialized and deserialized json objects when using jackson in java. 我希望在Java中使用jackson时能够为序列化和反序列化的json对象使用不同的名称。 To be a bit more concrete: I am getting data from an API that is using one name standard on their JSON attributes, but my endpoints use a different one, and as I in this case just want to pass the data along I would like to be able to translate the attributes to my name standard. 更具体一点:我正在从API中获取数据,该API在其JSON属性上使用一种名称标准,但是我的端点使用了另一种名称,因此在这种情况下,我只想传递数据能够将属性转换为我的名字标准。

I have read similar questions on here, but I simply can't seem to get it working. 我在这里读过类似的问题,但我似乎无法使其正常运行。

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

That is my latest attempt. 那是我最近的尝试。 problem with this is that it always returns null, so the setter is not used. 问题是它总是返回null,所以不使用setter。

I have also tried: 我也尝试过:

@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;
}

This sort of works. 这类作品。 It can deserialize default_reference . 它可以反序列化default_reference Problem is that in my JSON response I get both default_reference and defaultReference . 问题是在JSON响应中,我同时获得了default_referencedefaultReference Preferably I would only get defaultReference . 最好我只会得到defaultReference

Has anyone done anything similar and see what is wrong with what I've tried? 有没有人做过类似的事情,看看我尝试过的地方出了什么问题?

You're on the right track. 您走在正确的轨道上。 Here's an example of this working with a test JSON document. 这是使用测试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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM