jackjson
https://github.com/FasterXML/jackson-docs
https://github.com/FasterXML/jackson-core
https://github.com/FasterXML/jackson-databind
https://github.com/FasterXML/jackson-annotations
ObjectMapper
http://www.studytrails.com/java/json/jackson-create-json/
http://tutorials.jenkov.com/java-json/jackson-objectmapper.html
JackJson - JSON to Java
Annotation
https://github.com/FasterXML/jackson-docs/wiki/JacksonAnnotations
http://tutorials.jenkov.com/java-json/jackson-annotations.html
general annotation | read or write | description |
---|---|---|
@JsonIgnore | read + write | 忽略某个字段 |
@JsonIgnoreProperties | read + write | 忽略多个字段,ignoreUnknown=true可未知属性 |
@JsonProperty | read + write | 重命名字段 |
@JsonNaming | read + write | 自定义属性序列化或反序列化规则 |
@JsonFormat | read + write | 时间格式化,有时区问题 |
@JsonInclude | write | 忽略满足条件的属性,如null |
@JsonValue | write | 序列化对象为返回值,如把Enum序列化为code |
@JsonCreator | read | 反序列化指定值为对象,如把code序列化为Enum |
@JsonDeserialize | read | 反序列为指定的接口或是泛型时,用来指定实际的类型 |
Features
JsonParser Features
general featrue | default | description |
---|---|---|
ALLOW_UNQUOTED_FIELD_NAMES | false | 允许字段名称没有双引号 |
ALLOW_SINGLE_QUOTES | false | 允许字段名称和值使用单引号 |
ALLOW_NUMERIC_LEADING_ZEROS | false | 允许以0开头的数字 |
Serialization Features
general featrue | default | description |
---|---|---|
INDENT_OUTPUT | false | 格式化输出json,测试时有用 |
Deserialization Features
general featrue | default | description |
---|---|---|
FAIL_ON_UNKNOWN_PROPERTIES | true | 有未知的属性时报错 |
Serialization Inclusion
序列化时,是否显示某些属性,如Include.NOT_NULL
表示如果字段值为null,则序列化输出时不显示该字段
全局设置:setSerializationInclusion(Include.NON_NULL)
单个设置:@JsonInclude(JsonInclude.Include.NON_NULL)
Date Format
默认在java.uti.Date和时间戳之间序列化和反序列化
全局设置:setDateFormat(new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”))
单个设置: @JsonFormat(pattern = “yyyy-MM-dd HH:mm:ss”,timezone = “Asia/Shanghai”)
@JsonFormat有时区问题,参考:
https://stackoverflow.com/questions/46011703/set-current-timezone-to-jsonformat-timezone-value
https://github.com/FasterXML/jackson-databind/issues/1266
Property Naming Strategy
自定义属性序列化策略,比如下划线转骆峰
全局设置: setPropertyNamingStrategy(PropertyNamingStrategy.SnakeCaseStrategy.SNAKE_CASE)
单个设置:@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
General Configure
ObjectMapper objectMapper = new ObjectMapper()
.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true)
.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true)
.configure(JsonParser.Feature.ALLOW_NUMERIC_LEADING_ZEROS, true)
.configure(SerializationFeature.INDENT_OUTPUT,true)
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false)
.setSerializationInclusion(JsonInclude.Include.NON_NULL)
.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));