Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

}
like image 885
Luckycode Avatar asked Apr 22 '26 10:04

Luckycode


2 Answers

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.
like image 185
Manos Nikolaidis Avatar answered Apr 25 '26 01:04

Manos Nikolaidis


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);
like image 45
august0490 Avatar answered Apr 24 '26 23:04

august0490



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!