关于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均不解析
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值