5

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?

munHunger
  • 2,572
  • 5
  • 34
  • 63
  • See: https://stackoverflow.com/questions/8560348/different-names-of-json-property-during-serialization-and-deserialization – yinon Jun 26 '17 at 12:30

2 Answers2

5

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"}
    }
}
ck1
  • 5,243
  • 1
  • 21
  • 25
0

Another Alternative is


    @JsonSetter("default_reference")
    public void setDefaultReference(String defaultReference) {
        this.defaultReference = defaultReference;
    }

    @JsonGetter("defaultReference")
    public String getDefaultReference() {
        return defaultReference;
    }

Jin Lim
  • 1,759
  • 20
  • 24