Reputation: 3001
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?
Upvotes: 5
Views: 5378
Reputation: 2152
Another Alternative is
@JsonSetter("default_reference")
public void setDefaultReference(String defaultReference) {
this.defaultReference = defaultReference;
}
@JsonGetter("defaultReference")
public String getDefaultReference() {
return defaultReference;
}
Upvotes: 0
Reputation: 5443
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"}
}
}
Upvotes: 5