配置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>
*/