Jackson JSON field mapping capitalization?

I solve this problem by:

    @Getter
    @Setter
    static class UserInfo {
        //@JsonProperty("UUID")
        private String UUID = "11";
        private String UserName = "22";
        private String userName = "33";
        private String user_Name = "44";
        private String user_name = "55";
        private String User_name = "66";
        private boolean HasDeleted=true;
        private boolean hasDeleted=true;
        private boolean has_Deleted=true;
        private boolean has_deleted=true;
        private boolean HAS_DELETED=true;
    }

    public static void main(String[] args) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE);
        objectMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);

        String s = objectMapper.writeValueAsString(new UserInfo());
        System.out.println(s);


        UserInfo userInfo = objectMapper.readValue(s, UserInfo.class);
        System.out.println(objectMapper.writeValueAsString(userInfo));
    }

output:

{"UUID":"11","UserName":"22","userName":"33","user_Name":"44","user_name":"55","User_name":"66","HasDeleted":true,"hasDeleted":true,"has_Deleted":true,"has_deleted":true,"HAS_DELETED":true}

Add @JsonProperty on the setter that matches the property name in your received JSON string:

@JsonProperty("MDReqID")
public void setMDReqID(String MDReqID) {
    this.MDReqID = MDReqID;
}

Additionally add @JsonProperty annotation to the getter as well for your output to appear in the conventional format:

@JsonProperty("mDReqID")
public String getMDReqID() {
    return MDReqID;
}

Now you can name your variable whatever you like:

private String mdReqID;

Since your setter method is named setMDReqID(…) Jackson assumes the variable is named mDReqID because of the Java naming conventions (variables should start with lower case letters).

If you really want a capital letter use the @JsonProperty annotation on the setter (or - for serialization - on the getter) like this:

@JsonProperty("MDReqID")
public void setMDReqID(String MDReqID) {
    this.MDReqID = MDReqID;
}

You can also do

@JsonNaming(PropertyNamingStrategy.UpperCamelCaseStrategy.class)

on the class to capitalise all property names in the JSON message

Tags:

Java

Json

Jackson