配置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);
}
/**
* 该特性允许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>
*/