Luckycode
Luckycode

Reputation: 59

Duplicate Values while using ObjectMapper of Jackson

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

Answers (2)

august0490
august0490

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

Manos Nikolaidis
Manos Nikolaidis

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 :

  1. 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;
    }
    
  2. Use a more recent version of Jackson as you seem to be using 1.8 from 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

Related Questions