Jackson - ObjectMapper 类

  • 简介

    ObjectMapper 是 Jackson 库的主要参与者类。 ObjectMapper 类 ObjectMapper 提供了从基本 POJO(普通旧 Java 对象)或从通用 JSON 树模型 (JsonNode) 读取和写入 JSON 的功能,以及用于执行转换的相关功能。 它也是高度可定制的,既可以处理不同风格的 JSON 内容,也可以支持更高级的对象概念,例如多态性和对象标识。 ObjectMapper 还充当更高级的 ObjectReader 和 ObjectWriter 类的工厂。
  • 类定义

    以下是 com.fasterxml.jackson.databind.ObjectMapper 类的声明 −
    
    public class ObjectMapper
       extends ObjectCodec
          implements Versioned, Serializable
    
  • 嵌套类

    序号 Class & 描述
    1 static class ObjectMapper.DefaultTypeResolverBuilder
    自定义的 TypeResolverBuilder,提供与所谓的“默认类型”一起使用的类型解析器构建器(有关详细信息,请参阅 enableDefaultTyping())。
    2 static class ObjectMapper.DefaultTyping
    enumeration 与 enableDefaultTyping() 一起使用,以指定应该使用哪种类型(类)的默认类型。
  • 属性

    • protected DeserializationConfig _deserializationConfig- 定义序列化过程的基本全局设置的配置对象。
    • protected DefaultDeserializationContext _deserializationContext - 蓝图上下文对象;存储在这里以允许自定义子类。
    • protected InjectableValues _injectableValues - 在反序列化 POJO 中注入值的提供者。
    • protected JsonFactory _jsonFactory - 工厂用于根据需要创建 JsonParser 和 JsonGenerator 实例。
    • protected SimpleMixInResolver _mixIns - 定义如何应用混入注解的映射:键是接收附加注解的类型,值是具有要“混入”的注解的类型。
    • protected ConfigOverrides _propertyOverrides - 当前活动的按类型配置覆盖,由声明的属性类型访问。
    • protected Set<Object> _registeredModuleTypes - 一组模块类型(根据已注册的 Module.getTypeId();跟踪是否启用了 MapperFeature.IGNORE_DUPLICATE_MODULE_REGISTRATIONS,以便可以忽略重复的注册调用(主要是避免多次添加相同的处理程序)。
    • protected ConcurrentHashMap<JavaType,JsonDeserializer<Object>> _rootDeserializers - 我们将使用单独的主级 Map 来跟踪根级反序列化器。
    • protected SerializationConfig _serializationConfig - 定义序列化过程的基本全局设置的配置对象。
    • protected SerializerFactory _serializerFactory - 用于构建序列化器的序列化器工厂。
    • protected DefaultSerializerProvider _serializerProvider - 管理对用于序列化的序列化程序的访问的对象,包括缓存。
    • protected SubtypeResolver _subtypeResolver - 用于注册子类型的东西,根据需要将它们解析为超级/子类型。
    • protected TypeFactory _typeFactory - 用于创建 JavaType 实例的特定工厂;需要允许模块添加更多自定义类型处理(主要是为了支持非 Java JVM 语言的类型)。
    • protected static AnnotationIntrospector DEFAULT_ANNOTATION_INTROSPECTOR  
    • protected static BaseSettings DEFAULT_BASE - 基本设置包含用于所有 ObjectMapper 实例的默认值。
    • protected static VisibilityChecker<?> STD_VISIBILITY_CHECKER  
  • 构造方法

    序号 构造方法 & 描述
    1 ObjectMapper()
    默认构造函数,将根据需要构造默认的 JsonFactory,使用 SerializerProvider 作为其 SerializerProvider,使用 BeanSerializerFactory 作为其 SerializerFactory。
    2 ObjectMapper(JsonFactory jf)
    构造使用指定 JsonFactory 来构造必要的 JsonParsers 和/或 JsonGenerators 的实例。
    3 ObjectMapper(JsonFactory jf, SerializerProvider sp, DeserializerProvider dp)
    构造使用指定 JsonFactory 来构造必要的 JsonParsers 和/或 JsonGenerators 的实例,并使用给定的提供程序来访问序列化器和反序列化器。
    4 protected ObjectMapper(ObjectMapper src)
    Copy-constructor,主要用于支持 copy()。
  • 方法

    序号 方法
    1 protected void _checkInvalidCopy(Class<?> exp)  
    2 protected void _configAndWriteValue(JsonGenerator g, Object value) 
    3 protected Object _convert(Object fromValue, JavaType toValueType) 
    4 protected JsonDeserializer<Object> _findRootDeserializer(DeserializationContext ctxt, JavaType valueType) 
    5 protected JsonToken _initForReading(JsonParser p) 
    6 protected ObjectReader _newReader(DeserializationConfig config) 
    7 protected ObjectReader _newReader(DeserializationConfig config, JavaType valueType, Object valueToUpdate, FormatSchema schema, InjectableValues injectableValues) 
    8 protected ObjectWriter _newWriter(SerializationConfig config) 
    9 protected ObjectWriter _newWriter(SerializationConfig config, FormatSchema schema) 
    10 protected ObjectWriter _newWriter(SerializationConfig config, JavaType rootType, PrettyPrinter pp) 
    11 protected Object _readMapAndClose(JsonParser p0, JavaType valueType)  
    12 protected Object _readValue(DeserializationConfig cfg, JsonParser p, JavaType valueType) 
    13 protected DefaultSerializerProvider _serializerProvider(SerializationConfig config) 
    14 protected Object _unwrapAndDeserialize(JsonParser p, DeserializationContext ctxt, DeserializationConfig config, JavaType rootType, JsonDeserializer<Object> deser)  
    15 protected void _verifySchemaType(FormatSchema schema)  
    16 void acceptJsonFormatVisitor(Class<?> type, JsonFormatVisitorWrapper visitor) 
    17 void acceptJsonFormatVisitor(JavaType type, JsonFormatVisitorWrapper visitor) 
    18 ObjectMapper addHandler(DeserializationProblemHandler h) 
    19 ObjectMapper addMixIn(Class<?> target, Class<?> mixinSource) 
    20 boolean canDeserialize(JavaType type) 
    21 boolean canDeserialize(JavaType type, AtomicReference<Throwable> cause) 
    22 boolean canSerialize(Class<?> type) 
    23 boolean canSerialize(Class<?> type, AtomicReference<Throwable> cause) 
    24 ObjectMapper clearProblemHandlers() 
    25 MutableConfigOverride configOverride(Classlt;?> type) 
    26 ObjectMapper configure(DeserializationFeature f, boolean state) 
    27 ObjectMapper configure(JsonGenerator.Feature f, boolean state) 
    28 ObjectMapper configure(JsonParser.Feature f, boolean state) 
    29 ObjectMapper configure(MapperFeature f, boolean state) 
    30 ObjectMapper configure(SerializationFeature f, boolean state) 
    31 JavaType constructType(Type t) 
    32 <T> T convertValue(Object fromValue, Class<T> toValueType) 
    33 <T> T convertValue(Object fromValue, JavaType toValueType) 
    34 <T> T convertValue(Object fromValue, TypeReference<?> toValueTypeRef) 
    35 ObjectMapper copy() 
    36 ArrayNode createArrayNode() 
    37 ObjectNode createObjectNode() 
    38 protected ClassIntrospector defaultClassIntrospector() 
    39 ObjectMapper disable(DeserializationFeature feature) 
    40 ObjectMapper disable(DeserializationFeature first, DeserializationFeature... f) 
    41 ObjectMapper disable(JsonGenerator.Feature... features) 
    42 ObjectMapper disable(JsonParser.Feature... features) 
    43 ObjectMapper disable(MapperFeature... f) 
    44 ObjectMapper disable(SerializationFeature f) 
    45 ObjectMapper disable(SerializationFeature first, SerializationFeature... f) 
    46 ObjectMapper disableDefaultTyping() 
    47 ObjectMapper enable(DeserializationFeature feature) 
    48 ObjectMapper enable(DeserializationFeature first, DeserializationFeature... f) 
    49 ObjectMapper enable(JsonGenerator.Feature... features) 
    50 ObjectMapper enable(JsonParser.Feature... features) 
    51 ObjectMapper enable(MapperFeature... f) 
    52 ObjectMapper enable(SerializationFeature f) 
    53 ObjectMapper enable(SerializationFeature first, SerializationFeature... f) enabling specified DeserializationConfig features.
    54 ObjectMapper enableDefaultTyping() 
    55 ObjectMapper enableDefaultTyping(ObjectMapper.DefaultTyping dti) 
    56 ObjectMapper enableDefaultTyping(ObjectMapper.DefaultTyping applicability, JsonTypeInfo.As includeAs) 
    57 ObjectMapper enableDefaultTypingAsProperty(ObjectMapper.DefaultTyping applicability, String propertyName) 
    58 ObjectMapper findAndRegisterModules() 
    59 Class<?> findMixInClassFor(Class<?> cls)  
    60 static List<Module> findModules() 
    61 static List<Module> findModules(ClassLoader classLoader) 
    62 DateFormat getDateFormat()  
    63 DeserializationConfig getDeserializationConfig() 
    64 DeserializationContext getDeserializationContext() 
    65 JsonFactory getFactory() 
    66 InjectableValues getInjectableValues()  
    67 JsonFactory getJsonFactory() 
    68 JsonNodeFactory getNodeFactory() 
    69 PropertyNamingStrategy getPropertyNamingStrategy() 
    70 SerializationConfig getSerializationConfig() 
    71 SerializerFactory getSerializerFactory() 
    72 SerializerProvider getSerializerProvider() 
    73 SerializerProvider getSerializerProviderInstance() 
    74 SubtypeResolver getSubtypeResolver() 
    75 TypeFactory getTypeFactory()  
    76 VisibilityChecker<?> getVisibilityChecker() 
    77 boolean isEnabled(DeserializationFeature f) 
    78 boolean isEnabled(JsonFactory.Feature f) 
    79 boolean isEnabled(JsonGenerator.Feature f)  
    80 boolean isEnabled(JsonParser.Feature f)  
    81 boolean isEnabled(MapperFeature f) 
    82 boolean isEnabled(SerializationFeature f) 
    83 int mixInCount()  
    84 ObjectReader reader() 
    85 ObjectReader reader(Base64Variant defaultBase64) 
    86 ObjectReader reader(Class<?> type) 
    87 ObjectReader reader(ContextAttributes attrs) 
    88 ObjectReader reader(DeserializationFeature feature) 
    89 ObjectReader reader(DeserializationFeature first, DeserializationFeature... other) 
    90 ObjectReader reader(FormatSchema schema) 
    91 ObjectReader reader(InjectableValues injectableValues) 
    92 ObjectReader reader(JavaType type) 
    93 ObjectReader reader(JsonNodeFactory f) for constructing JSON trees.
    94 ObjectReader reader(TypeReference<?> type) 
    95 ObjectReader readerFor(Class<?> type) 
    96 ObjectReader readerFor(JavaType type) 
    97 ObjectReader readerFor(TypeReference<?> type) 
    98 ObjectReader readerForUpdating(Object valueToUpdate) 
    99 ObjectReader readerWithView(Class<?> view) 
    100 JsonNode readTree(byte[] content) 
    101 JsonNode readTree(File file) 
    102 JsonNode readTree(InputStream in) 
    103 <T extends TreeNode> T readTree(JsonParser p) 
    104 JsonNode readTree(Reader r) 
    105 JsonNode readTree(String content) 
    106 JsonNode readTree(URL source) 
    107 <T> T readValue(byte[] src, Class<T> valueType)  
    108 <T> T readValue(byte[] src, int offset, int len, Class<T> valueType) 
    109 <T> T readValue(byte[] src, int offset, int len, JavaType valueType)  
    110 <T> T readValue(byte[] src, int offset, int len, TypeReference valueTypeRef)  
    111 <T> T readValue(byte[] src, JavaType valueType)  
    112 <T> T readValue(byte[] src, TypeReference valueTypeRef)  
    113 <T> T readValue(DataInput src, Class<T> valueType)  
    114 <T> T readValue(DataInput src, JavaType valueType)  
    115 <T> T readValue(File src, Class<T> valueType) 
    116 <T> T readValue(File src, JavaType valueType) 
    117 <T> T readValue(File src, TypeReference valueTypeRef) 
    118 <T> T readValue(InputStream src, Class<T> valueType)  
    119 <T> T readValue(InputStream src, JavaType valueType)  
    120 <T> T readValue(InputStream src, TypeReference valueTypeRef)  
    121 <T> T readValue(JsonParser p, Class<T> valueType) - Method to deserialize JSON content into a non-container type (it can be an array type, however): typically a bean, array or a wrapper type (like Boolean). 
    122 <T> T readValue(JsonParser p, JavaType valueType) 
    123 <T> T readValue(JsonParser p, ResolvedType valueType) 
    124 <T> T readValue(JsonParser p, TypeReference<?> valueTypeRef) 
    125 <T> T readValue(Reader src, Class<T> valueType)  
    126 <T> T readValue(Reader src, TypeReference valueTypeRef)  
    127 <T> T readValue(String content, Class<T> valueType) 
    128 <T> T readValue(String content, JavaType valueType) 
    129 <T> T readValue(String content, TypeReference valueTypeRef) 
    130 <T> T readValue(URL src, Class<T> valueType) 
    131 <T> T readValue(URL src, JavaType valueType)  
    132 <T> T readValue(URL src, TypeReference valueTypeRef) 
    133 <T> MappingIterator<T>readValues(JsonParser p, Class<T> valueType) 
    134 <T> MappingIterator<T>readValues(JsonParser p, JavaType valueType) 
    135 <T> MappingIterator<T>readValues(JsonParser p, ResolvedType valueType) 
    136 <T> MappingIterator<T>readValues(JsonParser p, TypeReference<?>valueTypeRef) 
    137 ObjectMapper registerModule(Module module) 
    138 ObjectMapper registerModules(Iterable<Module> modules) 
    139 ObjectMapper registerModules(Module... modules) 
    140 void registerSubtypes(NamedType... types) 
    141 ObjectMapper setAnnotationIntrospector(AnnotationIntrospector ai) 
    142 ObjectMapper setAnnotationIntrospectors(AnnotationIntrospector serializerAI, AnnotationIntrospector deserializerAI) 
    143 ObjectMapper setBase64Variant(Base64Variant v) 
    144 ObjectMapper setConfig(DeserializationConfig config) 
    145 ObjectMapper setConfig(SerializationConfig config) serialization-specific configuration settings.
    146 ObjectMapper setDateFormat(DateFormat dateFormat) 
    147 ObjectMapper setDefaultPrettyPrinter(PrettyPrinter pp) 
    148 ObjectMapper setDefaultTyping(TypeResolverBuilder<?> typer) 
    149 ObjectMapper setFilterProvider(FilterProvider filterProvider) 
    150 Object setHandlerInstantiator(HandlerInstantiator hi) 
    151 ObjectMapper setInjectableValues(InjectableValues injectableValues) 
    152 ObjectMapper setLocale(Locale l) 
    153 void setMixInAnnotations(Map<Class<?>,Class<?>> sourceMixins) 
    154 ObjectMapper setMixInResolver(ClassIntrospector.MixInResolver resolver) 
    155 ObjectMapper setMixIns(Map<Class<?>,Class<?>> sourceMixins) 
    156 ObjectMapper setNodeFactory(JsonNodeFactory f) 
    157 ObjectMapper setPropertyInclusion(JsonInclude.Value incl) 
    158 ObjectMapper setPropertyNamingStrategy(PropertyNamingStrategy s) 
    159 ObjectMapper setSerializationInclusion(JsonInclude.Include incl) 
    160 ObjectMapper setSerializerFactory(SerializerFactory f) 
    161 ObjectMapper setSerializerProvider(DefaultSerializerProvider p) 
    162 ObjectMapper setSubtypeResolver(SubtypeResolver str) 
    163 ObjectMapper setTimeZone(TimeZone tz) 
    164 ObjectMapper setTypeFactory(TypeFactory f) 
    165 ObjectMapper setVisibility(PropertyAccessor forMethod, JsonAutoDetect.Visibility visibility) 
    166 ObjectMapper setVisibility(VisibilityChecker<?> vc) 
    167 void setVisibilityChecker(VisibilityChecker<?> vc) 
    168 JsonParser treeAsTokens(TreeNode n) 
    169 <T> T treeToValue(TreeNode n, Class<T> valueType) 
    170 <T extends JsonNode> T valueToTree(Object fromValue) 
    171 Version version() 
    172 ObjectWriter writer() 
    173 ObjectWriter writer(Base64Variant defaultBase64) 
    174 ObjectWriter writer(CharacterEscapes escapes) 
    175 ObjectWriter writer(ContextAttributes attrs) 
    176 ObjectWriter writer(DateFormat df) 
    177 ObjectWriter writer(FilterProvider filterProvider) 
    178 ObjectWriter writer(FormatSchema schema) 
    179 ObjectWriter writer(PrettyPrinter pp) 
    180 ObjectWriter writer(SerializationFeature feature) 
    181 ObjectWriter writer(SerializationFeature first, SerializationFeature... other) 
    182 ObjectWriter writerFor(Class<?> rootType) 
    183 ObjectWriter writerFor(JavaType rootType) 
    184 ObjectWriter writerFor(TypeReference<?> rootType) 
    185 ObjectWriter writerWithDefaultPrettyPrinter() 
    186 ObjectWriter writerWithType(Class<?> rootType) 
    187 ObjectWriter writerWithType(JavaType rootType) 
    188 ObjectWriter writerWithType(TypeReference<?> rootType) 
    189 ObjectWriter writerWithView(Class<?> serializationView) 
    190 void writeTree(JsonGenerator jgen, JsonNode rootNode) 
    191 void writeTree(JsonGenerator jgen, TreeNode rootNode)  
    192 void writeValue(DataOutput out, Object value)  
    193 void writeValue(File resultFile, Object value) 
    194 void writeValue(JsonGenerator g, Object value) 
    195 void writeValue(OutputStream out, Object value) 
    196 void writeValue(Writer w, Object value) 
    197 byte[] writeValueAsBytes(Object value) 
    198 String writeValueAsString(Object value) 
  • 继承的方法

    这个类继承了以下类的方法:
    • java.lang.Object
  • ObjectMapper 示例

    使用您选择的任何编辑器创建以下 java 程序,例如 C:/> Jackson_WORKSPACE
    文件: JacksonTester.java
    
    import java.io.IOException;
    import com.fasterxml.jackson.core.JsonParseException;
    import com.fasterxml.jackson.databind.JsonMappingException;
    import com.fasterxml.jackson.databind.ObjectMapper;
    public class JacksonTester {
       public static void main(String args[]){
       
          ObjectMapper mapper = new ObjectMapper();
          String jsonString = "{\"name\":\"Mahesh\", \"age\":21}";
          
          //map json to student
          try{
             Student student = mapper.readValue(jsonString, Student.class);
             
             System.out.println(student);
             
             jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(student);
             
             System.out.println(jsonString);
          }
          catch (JsonParseException e) { e.printStackTrace();}
          catch (JsonMappingException e) { e.printStackTrace(); }
          catch (IOException e) { e.printStackTrace(); }
       }
    }
    class Student {
       private String name;
       private int age;
       public Student(){}
       public String getName() {
          return name;
       }
       public void setName(String name) {
          this.name = name;
       }
       public int getAge() {
          return age;
       }
       public void setAge(int age) {
          this.age = age;
       }
       public String toString(){
          return "Student [ name: "+name+", age: "+ age+ " ]";
       }
    }
    
    验证结果
    使用 javac 编译器编译类,如下所示:
    
    C:\Jackson_WORKSPACE>javac JacksonTester.java
    
    现在运行 jacksonTester 来查看结果:
    
    C:\Jackson_WORKSPACE>java JacksonTester
    
    验证输出
    
    Student [ name: Mahesh, age: 21 ]
    {
      "name" : "Mahesh",
      "age" : 21
    }
    
Jackson - ObjectMapper Class