通过 lesson 1,2 我们学会了基础的 jackson 转化, 但在实际生产中, 我们往往要对 ObjectMapper 进行全局属性上的设置,来满足一定的需要。
如 不存在的属性不报错等...
下面对 ObjectMapper 常用的属性进行讲解:
========= 序列化的一些设置 ==============
// SerializationFeature for changing how JSON is written
// to enable standard indentation ("pretty-printing"):
mapper.enable(SerializationFeature.INDENT_OUTPUT);
// 设置pojo为null 时, 进行序列化不报错
// to allow serialization of "empty" POJOs (no properties to serialize)
// (without this setting, an exception is thrown in those cases)
mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
// to write java.util.Date, Calendar as number (timestamp):
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
=====================================================
=========== 反序列化的一些设置 ==============
// DeserializationFeature for changing how JSON is read as POJOs:
// to prevent exception when encountering unknown property:
// 设置 对于未知的属性也不报错
// 即pojo中无此属性,json 串中有此属性
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
// to allow coercion of JSON empty String ("") to null Object value:
mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
In addition, you may need to change some of low-level JSON parsing, generation details:
=================================================
========== Json 转换的一些设置 ===================
// JsonParser.Feature for configuring parsing settings:
// to allow C/C++ style comments in JSON (non-standard, disabled by default)
// (note: with Jackson 2.5, there is also `mapper.enable(feature)` / `mapper.disable(feature)`)
mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
// to allow (non-standard) unquoted field names in JSON:
mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
// to allow use of apostrophes (single quotes), non standard
// 设置 json 串 允许使用 单引号 “ ‘ ’” 进行分割 .
// 如 : "{'name':'Szh', 'age':24}"
mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
============================================
============= JsonGenerator Feature ===========
// JsonGenerator.Feature for configuring low-level JSON generation:
// to force escaping of non-ASCII characters:
mapper.configure(JsonGenerator.Feature.ESCAPE_NON_ASCII, true);
完整的序列化 与 反序列化的 设置:
https://github.com/FasterXML/jackson-databind/wiki/JacksonFeatures
又可以细分为 3类 :
- Serialization features (writing POJOs as JSON and other formats)
- Deserialization features (reading JSON and other formats as POJOs)