20221116 ObjectMapper
概述
com.fasterxml.jackson.databind.ObjectMapper
门面类,提供几乎所有的 JSON 操作方法
databind
模块中的类
线程安全,前提是不修改对象映射器的配置
公共方法
模块(Module)
Module registration, discovery
-
registerModule
-
registerModules
-
getRegisteredModuleIds
-
findModules
-
findAndRegisterModules
创建 JsonGenerator 工厂方法
Factory methods for creating JsonGenerators
- createGenerator
创建 JsonParser 工厂方法
Factory methods for creating JsonParsers
-
createParser
-
createNonBlockingByteArrayParser
配置:对象访问
Configuration: main config object access
-
getSerializationConfig
-
getDeserializationConfig
-
getDeserializationContext
配置:序列化、反序列化工厂
Configuration: ser/deser factory, provider access
-
setSerializerFactory
-
getSerializerFactory
-
setSerializerProvider
-
getSerializerProvider
-
getSerializerProviderInstance
配置:混合注解
Configuration: mix-in annotations
-
setMixIns
-
addMixIn
-
setMixInResolver
-
findMixInClassFor
-
mixInCount
配置:自省
Configuration, introspection
-
getVisibilityChecker
-
setVisibility
-
setVisibility
-
getSubtypeResolver
-
setSubtypeResolver
-
setAnnotationIntrospector
-
setAnnotationIntrospectors
-
setPropertyNamingStrategy
-
getPropertyNamingStrategy
-
setAccessorNaming
-
setDefaultPrettyPrinter
-
setPolymorphicTypeValidator
-
getPolymorphicTypeValidator
配置:全局默认配置
Configuration: global-default/per-type override settings
-
setSerializationInclusion
-
setDefaultPropertyInclusion
-
setDefaultSetterInfo
-
setDefaultVisibility
-
setDefaultMergeable
-
setDefaultLeniency
子类型注册
Subtype registration
- registerSubtypes
默认类型
Default typing (automatic polymorphic types): current (2.10)
-
activateDefaultTyping
-
activateDefaultTypingAsProperty
-
deactivateDefaultTyping
-
setDefaultTyping
配置:强制配置
Configuration, config, coercion overrides
-
configOverride
-
coercionConfigDefaults
-
coercionConfigFor
配置:基本类型处理
Configuration, basic type handling
-
getTypeFactory
-
setTypeFactory
-
constructType
配置:反序列化
Configuration, deserialization
-
getNodeFactory
-
setNodeFactory
-
setConstructorDetector
-
addHandler
-
clearProblemHandlers
-
setConfig
配置:序列化
Configuration, serialization
-
setFilters
-
setFilterProvider
-
setBase64Variant
-
setConfig
配置:其他
Configuration, other
-
tokenStreamFactory
-
getFactory
-
setDateFormat
-
getDateFormat
-
setHandlerInstantiator
-
setInjectableValues
-
getInjectableValues
-
setLocale
-
setTimeZone
-
setDefaultAttributes
配置:简单特征 Feature
Configuration, simple features:
MapperFeature、SerializationFeature、DeserializationFeature、JsonParser.Feature、JsonGenerator.Feature、JsonFactory.Feature、StreamReadFeature、StreamWriteFeature
-
isEnabled
-
configure
-
enable
-
disable
公共 API (来自 ObjectCodec ):反序列化
Public API (from ObjectCodec): deserialization
(mapping from JSON to Java types); main methods
- readValue
公共 API (不在 ObjectCodec ):反序列化
Public API not included in ObjectCodec: deserialization
(mapping from JSON to Java types)
- readTree
公共 API (来自 ObjectCodec ):序列化
Public API (from ObjectCodec): serialization
(mapping from Java types to Json)
- writeValue
公共 API(来自 TreeCodec):树模型支持
Public API (from TreeCodec via ObjectCodec): Tree Model support
-
writeTree
-
createObjectNode
-
createArrayNode
-
missingNode
-
nullNode
-
treeAsTokens
-
treeToValue
-
valueToTree
扩展公共 API:存取器
Extended Public API, accessors
-
canSerialize
-
canDeserialize
扩展公共 API:反序列化
Extended Public API, deserialization,
convenience methods
- readValue
扩展公共 API:序列化
Extended Public API: serialization
(mapping from Java types to JSON)
-
writeValue
-
writeValueAsString
-
writeValueAsBytes
扩展公共 API:构造 ObjectWriter
Extended Public API: constructing ObjectWriters
for more advanced configuration
-
writer
-
writerWithView
-
writerFor
-
writerWithDefaultPrettyPrinter
扩展公共 API:构造 ObjectReader
Extended Public API: constructing ObjectReaders
for more advanced configuration
-
reader
-
readerForUpdating
-
readerFor
-
readerForArrayOf
-
readerForListOf
-
readerForMapOf
-
readerWithView
扩展公共 API:便捷类型转换
Extended Public API: convenience type conversion
-
convertValue
-
updateValue
扩展公共 API:JSON Schema 生成
- acceptJsonFormatVisitor
基本用法
ObjectMapper
相关方法:
-
readValue
-
writeValue
转对象
// 序列化
String jsonString = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(user);
System.out.println(jsonString);
// 反序列化
user = objectMapper.readValue(jsonString, User.class);
System.out.println(user);
/*
{
"name" : "张三",
"age" : 18,
"birthDate" : 949494020000,
"likes" : [ "sing", "dance", "read" ]
}
User(name=张三, age=18, birthDate=Wed Feb 02 20:20:20 CST 2000, likes=[sing, dance, read])
*/
转对象 List
List<User> userList = CollUtil.toList(getUser(), getUser());
String jsonStr = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(userList);
System.out.println(jsonStr);
List<User> users = objectMapper.readValue(jsonStr, new TypeReference<List<User>>() {
});
System.out.println(users);
/*
[ {
"name" : "张三",
"age" : 18,
"birthDate" : 949494020000,
"likes" : [ "sing", "dance", "read" ]
}, {
"name" : "张三",
"age" : 18,
"birthDate" : 949494020000,
"likes" : [ "sing", "dance", "read" ]
} ]
[User(name=张三, age=18, birthDate=Wed Feb 02 20:20:20 CST 2000, likes=[sing, dance, read]), User(name=张三, age=18, birthDate=Wed Feb 02 20:20:20 CST 2000, likes=[sing, dance, read])]
*/
转 Map
Map<String, User> userMap = MapUtil.ofEntries(MapUtil.entry("1", getUser()), MapUtil.entry("2", getUser()));
String jsonStr = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(userMap);
System.out.println(jsonStr);
Map<String, User> map = objectMapper.readValue(jsonStr, new TypeReference<Map<String, User>>() {
});
System.out.println(map);
/*
{
"1" : {
"name" : "张三",
"age" : 18,
"birthDate" : 949494020000,
"likes" : [ "sing", "dance", "read" ]
},
"2" : {
"name" : "张三",
"age" : 18,
"birthDate" : 949494020000,
"likes" : [ "sing", "dance", "read" ]
}
}
{1=User(name=张三, age=18, birthDate=Wed Feb 02 20:20:20 CST 2000, likes=[sing, dance, read]), 2=User(name=张三, age=18, birthDate=Wed Feb 02 20:20:20 CST 2000, likes=[sing, dance, read])}
*/
常用方法
时间格式设置
-
setDateFormat
-
getDateFormat
objectMapper.setDateFormat(DateUtil.newSimpleFormat(DatePattern.NORM_DATETIME_PATTERN));
配置 Feature
-
isEnabled
-
configure
-
enable
-
disable
// 按字母表顺序序列化字段(若false,按字段声明的顺序)
boolean enabled = objectMapper.isEnabled(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY);
objectMapper.enable(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY);
读写 JSON
-
readValue
-
writeValue
-
writeValueAsString
参考【基本用法】
树模型
-
readTree
-
writeTree
ObjectReader
和 ObjectWriter
-
不可变对象,更轻量,可重用,如果需要多次创建对象,应该使用这两个类
-
可以通过
ObjectMapper
的工厂方法创建,也可以通过构造器创建 -
具有和
ObjectMapper
相同的常用方法
SerializationConfig 、DeserializationConfig
ObjectMapper
属性
protected SerializationConfig _serializationConfig;
protected DeserializationConfig _deserializationConfig;
关联 SerializationFeature
和 DeserializationFeature
JsonSerializer 和 JsonDeserializer
ObjectMapper
属性
protected DefaultSerializerProvider _serializerProvider;
protected SerializerFactory _serializerFactory;
protected DeserializationConfig _deserializationConfig;
protected DefaultDeserializationContext _deserializationContext;
配合 @JsonSerialize
和 @JsonDeserialize
一起使用
JsonMapper
com.fasterxml.jackson.databind.json.JsonMapper
ObjectMapper
的子类
从 2.10 版本开始出现
处理 JSON 时,更应该使用 JsonMapper
,就像处理 XML 时,使用 XmlMapper
目前和 ObjectMapper
在功能上几乎没有区别
推测是在未来的定位上,ObjectMapper
将作为基类,而在实际处理不同数据格式时,选用不同的实现
证据包括对 Feature 的处理上,JsonReadFeature
、JsonWriteFeature
、StreamReadFeature
、StreamWriteFeature
这四个细分的 Feature 也是从 2.10 版本开始出现,为了取代 JsonParser.Feature
、JsonGenerator.Feature
支持 Builder 模式创建对象
配置 Feature
支持 JsonReadFeature
、JsonWriteFeature