Why does Jackson display these values โ€‹โ€‹twice, otherwise?

I map the Java object to JSON using Jackson, this 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; } } 

Then the display code is as follows:

 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 areaJSON value at this point will be as follows:

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

Pay attention to several values โ€‹โ€‹with a different case.

What am I doing wrong?

+5
source share
3 answers

Jackson believes that the Id and Name fields are different from the properties returned by the getters because the case is different. Using standard JavaBeans naming conventions, Jackson introduces getter-specific fields called Id and Name , not Id and Name .

tl; dr matters.


There are two easy ways to solve this problem:

  • Remove the @JsonAutoDetect annotation of this class. I am sure that annotation defaults take precedence over ObjectMapper configuration. As an alternative:

  • Do not guess with ObjectMapper at all. Change @JsonAutoDetect on class to

     @JsonAutoDetect( fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE, creatorVisibility = Visibility.NONE ) 
+8
source

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

+1
source

I know this is an old post, but there is a simpler solution: use only annotation in the fields:

 @XmlRootElement @XmlAccessorType(XmlAccessType.FIELD) public class Area { public int id; 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; } } 

You can choose how to serialize the object: using a field or using properties. If you use fields, the getter and setter are ignored.

The problem in the code is created with the first letter in upper case : access to the field, property json - Id; access to getter, getId became id (the first letter after get is encoded in lower case).

0
source

All Articles