Jackson 反序列化时实现大小写不敏感设置

时间:2022-05-06 07:07:31

常用配置

?
1
2
3
4
5
6
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);//大小写脱敏 默认为false  需要改为tru

参考

?
1
com.fasterxml.jackson.databind.MapperFeature#ACCEPT_CASE_INSENSITIVE_PROPERTIES

使用注解方式:举例

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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 转换大小写问题

Jackson转换json时会把大写转换成小写

解决办法:

1、在变量时加上: @JsonProperty

2、在set/get方法加上:@JsonIgnore

以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://beijingngcc.blog.csdn.net/article/details/85009163