Implementing case insensitive settings when Jackson deserializes

  • 2021-10-13 07:23:26
  • OfStack

Common configuration


ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(Feature.IGNORE_UNKNOWN,true);
objectMapper.configure(Feature.WRITE_BIGDECIMAL_AS_PLAIN,true);
objectMapper.configure(JsonParser.Feature.ALLOW_MISSING_VALUES,true);
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);
objectMapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES,false);// Case desensitization   Default to false   Need to read tru

Reference


com.fasterxml.jackson.databind.MapperFeature#ACCEPT_CASE_INSENSITIVE_PROPERTIES

Using annotations: Examples


public static void main(String[] args) throws IOException {
        String x = "{\n"
            + "        \"TToUserName\":\"gh_a5624dd2db4e\",\n"
            + "        \"FFromUserName\":\"ochvq0Kn35VlnTAcIJ3fRBAZTQUY\""
            + "       }";
 
        ObjectMapper objectMapper = new ObjectMapper();
        Result map = objectMapper.readValue(x, Result.class);
        System.out.println(map);
        objectMapper.writeValue(System.out,map);
    }
  
    private static class Result { 
        private String ToUserName;
        private String FromUserName; 
        @JsonProperty("ToUserName")
        public String getToUserName() {
            return ToUserName;
        }
 
        @JsonProperty("TToUserName")
        public void setToUserName(String toUserName) {
            ToUserName = toUserName;
        }
 
        @JsonProperty("FromUserName")
        public String getFromUserName() {
            return FromUserName;
        }
 
        @JsonProperty("FFromUserName")
        public void setFromUserName(String fromUserName) {
            FromUserName = fromUserName;
        }
    }

Jackson Conversion Case Problem

Jackson converts uppercase to lowercase when converting json

Solution:

1. Add: @ JsonProperty to the variable

2. Add @ JsonIgnore to the set/get method


Related articles: