jackson使用

配置ObjectMapper

参考链接

ObjectMapper mapper = new ObjectMapper();
  • 配置要检测序列化的字段

    • 自动检测所有成员字段 auto-detect all member fields
    mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
    • 只有get方法的成员 but only public getters
    mapper.setVisibility(PropertyAccessor.GETTER, Visibility.NONE);
    • 1 没有set或者is方法 and none of “is-setters”
    setVisibility(PropertyAccessor.IS_GETTER, Visibility.NONE);
  • 禁止抛出异常

    • 返回的JSON字符串中含有我们并不需要的字段,那么当对应的实体类中不含有该字段时,会抛出一个异常
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);
  • 对于数字转换,是数字的标识符但不是数字的转换
mapper.configure(Feature.ALLOW_NON_NUMERIC_NUMBERS, true);
  • 该特性决定是否接受强制非数组(JSON)值到Java集合类型。如果允许,集合反序列化将尝试处理非数组值。
mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
  • 空JSON字符串可以等价于JSON null
mapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);

转换成指定的集合对象

public static <T> T readJson(String jsonStr, Class<?> collectionClass, Class<?>... elementClasses) throws Exception {
   ObjectMapper mapper = new ObjectMapper();
   JavaType javaType = mapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);
   return mapper.readValue(jsonStr, javaType);
}


  1. /**
    * 该特性允许parser可以识别"Not-a-Number" (NaN)标识集合作为一个合法的浮点数。 例如: allows (tokens are quoted contents, not including
    * quotes):
    * <ul>
    * <li>"INF" (for positive infinity), as well as alias of "Infinity"
    * <li>"-INF" (for negative infinity), alias "-Infinity"
    * <li>"NaN" (for other not-a-numbers, like result of division by zero)
    * </ul>
    */
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值