最近因为项目需要,对Jackson的使用进行了深入的学习,总结了几条使用心得,在此记录一下:
-
在做Json字符串转换为对象时,有时会出现对象中存在某属性,而json字符串没有此属性,缺省情况下会抛出异常。可通过以下两种方式配置不抛出异常:
- application.properties中进行全局配置:spring.jackson.deserialization.fail_on_unknown_properties=false
- 针对需要配置对象类,添加注解: @JsonIgnoreProperties(ignoreUnknown = true)
-
java类的属性,一般是小驼峰模式,如testStr。在转换为Json字符串时,可以控制json中属性的命名方式,如大驼峰,小驼峰,蛇形(下划线),不变等。
- 全局配置属性spring.jackson.property-naming-strategy
- UPPER_CAMEL_CASE - 大驼峰 (TestStr)
- LOWER_CAMEL_CASE - 小驼峰 (testStr)
- SNAKE_CASE - 下划线 (test_str)
- LOWER_CASE - 小写 (teststr)
- KEBAB_CASE - 减号 (test-str)
- 针对指定对象,添加注解@JsonNaming(PropertyNamingStrategy.???.class)
- @JsonNaming(PropertyNamingStrategy.UpperCamelCaseStrategy.class) - 大驼峰
- @JsonNaming(PropertyNamingStrategy.LowerDotCaseStrategy.class) - .分隔 test.str
- @JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class) - 下划线
- @JsonNaming(PropertyNamingStrategy.LowerCaseStrategy.class) - 小写
- @JsonNaming(PropertyNamingStrategy.KebabCaseStrategy.class) - 减号
其中有一点需要注意,对于从json字符串转换为实体对象时,即使设置了大驼峰等模式,使用对象属性名,也可以解析成功,即TestStr, testStr均可解析成功。
- 全局配置属性spring.jackson.property-naming-strategy
-
空属性是否序列化
- 全局配置spring.jackson.default-property-inclusion=non_null
- non_null: null不解析
- non_empty: 空字符’'和null均不解析
- 全局配置spring.jackson.default-property-inclusion=non_null