Json_Jackson_ lesson3 Jackson转换配置


通过 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类 :





https://github.com/FasterXML/jackson-databind/wiki/Deserialization%20Features























评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值