栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

关于Jackson Json与对象转换的几个配置笔记

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

关于Jackson Json与对象转换的几个配置笔记

最近因为项目需要,对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.default-property-inclusion=non_null
      • non_null: null不解析
      • non_empty: 空字符’'和null均不解析
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/445124.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号