Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Jackson mapping these values twice, in differing case?

Tags:

java

json

jackson

I'm mapping a Java object to JSON using Jackson, the object is a pretty simple pojo class that looks like this:

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonProperty;

@JsonAutoDetect
public class Area {
    @JsonProperty("Id")
    public int Id;
    @JsonProperty("Name")
    public String Name;

    public Area() {
        Name = "";
    }

    public int getId() {
        return Id;
    }

    public void setId(int id) {
        Id = id;
    }

    public String getName() {
        return Name;
    }

    public void setName(String Name) {
        this.Name = Name;
    }
}

The mapping code then looks like this:

ObjectMapper mapper = new ObjectMapper();

mapper.setVisibilityChecker(mapper.getSerializationConfig().getDefaultVisibilityChecker()
            .withFieldVisibility(JsonAutoDetect.Visibility.ANY)
            .withGetterVisibility(JsonAutoDetect.Visibility.NONE)
            .withSetterVisibility(JsonAutoDetect.Visibility.NONE)
            .withCreatorVisibility(JsonAutoDetect.Visibility.NONE));

areaJSON = mapper.writeValueAsString(area);

But the value of areaJSON at this point is then as follows:

{"id":0,"name":"","Name":"","Id":0}

Note the multiple values with differing case.

What am I doing wrong?

like image 207
Jordan Robinson Avatar asked May 05 '15 19:05

Jordan Robinson


2 Answers

Jackson thinks that the fields Id and Name are different properties from the ones returned by the getters because the case is different. Using standard JavaBeans naming conventions, Jackson infers the fields corresponding to the getters are named id and name, not Id and Name.

tl;dr case matters.


There are two simple ways to fix this problem:

  1. Remove the @JsonAutoDetect annotation from this class entirely. I'm pretty sure that the default annotation values are taking precedence over the ObjectMapper's configuration. Alternately:

  2. Don't muck with the ObjectMapper at all. Change the @JsonAutoDetect on the class to

    @JsonAutoDetect(
      fieldVisibility = Visibility.ANY,
      getterVisibility = Visibility.NONE,
      setterVisibility = Visibility.NONE,
      creatorVisibility = Visibility.NONE
    )
    
like image 190
Matt Ball Avatar answered Oct 29 '22 16:10

Matt Ball


You need to annotate getId method with @JsonProperty("Id"), otherwise getId will also be added with lowercase id.

like image 37
Muthee Avatar answered Oct 29 '22 17:10

Muthee