简体   繁体   中英

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. 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.

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.

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 . Problem is that in my JSON response I get both default_reference and defaultReference . Preferably I would only get 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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