Duplicate json property when converting java object to json string using jackson

We can also use the @JsonProperty("Name") annotation directly on the getters to avoid duplication.


So i do follow: how to specify jackson to only use fields - preferably globally

I add

@JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE)

before

public class LogLikeArticleDetail extends BaseObject

and the result that i want.

So can another solve that in getAsJson() function like:

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));
return mapper.writeValueAsString(this) ;

Thanks for @Sean Carpenter 's question and @kmb385 answer in link above.


It is actually not an issue. So, over here what happened was Jackson library was unable to match those fields automatically (there is no assumption of case unification), so you end up with twice the properties you expect.

The simple fix for this issue is to just add annotations to either getters/setters (either is fine.)

@JsonProperty("UserName")
public String getUserName() {
        return this.userName;
}

This issue was also raised in Jackson Github repo. You can find the answer in the following link.

https://github.com/FasterXML/jackson-databind/issues/1609


You can also do this per POJO using annotations. Add this string to the top of your class you'd like no auto detection on:

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

For example:

@JsonAutoDetect(fieldVisibility=JsonAutoDetect.Visibility.ANY, getterVisibility=JsonAutoDetect.Visibility.NONE,
        setterVisibility=JsonAutoDetect.Visibility.NONE, creatorVisibility=JsonAutoDetect.Visibility.NONE)
class Play {
    @JsonProperty("Name")
    private String name; 

    @JsonProperty("NickName")
    private String nickName; 

    public Play(){

    }

    public String getName() {
        return name;
    }

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

    public String getNickName() {
        return nickName;
    }

    public void setNickName(String nickName) {
        this.nickName = nickName;
    }
}

This will return the properties I've defined and not auto-detect the field names and add them to my returned JSON result.