Reputation: 59
My Bean class is as below. When the mapping happens, the JSON object contains duplicate values.
Response:
{"Id":"00PJ0000003mOgMMAU","Name":"web.xml","name":"web.xml","id":"00PJ0000003mOgMMAU"}
Why the values are getting duplicated?
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.annotate.JsonProperty;
@JsonIgnoreProperties(ignoreUnknown = true)
public class AttachmentsMapper
{
@JsonProperty(value = "Id")
private String Id;
@JsonProperty(value = "Name")
private String Name;
public String getId() {
return Id;
}
public void setId(String Id) {
this.Id = Id;
}
public String getName() {
return Name;
}
public void setName(String Name) {
this.Name = Name;
}
}
Upvotes: 3
Views: 5728
Reputation: 884
In Jackson 2 try to disable Jackson visibility for all the sources (getters, setters, fields, etc.) and then just enable the visibility for the object fields:
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
...
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.ALL, Visibility.NONE);
mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
Upvotes: 3
Reputation: 22254
It doesn't print duplicate the same field twice it prints 2 different fields that it finds. Jackson sees you want to print "name"
because you have a getter called getName()
and "Name"
because you have annotated the Name
field as @JsonProperty
with a different key. It sees different fields because "name"
!= "Name"
. Two solutions :
Move the annotation to the getter. The field is ignored by default because it's private E.g.
@JsonProperty(value = "Name")
public String getName() {
return Name;
}
com.codehaus
. Use 1.9 from there or even better use the latest from com.fasterxml
. I tried your code as it is with 1.9 and it worked without moving the annotation.Upvotes: 5