ObjectMapper is the main actor class of Jackson library. ObjectMapper
class provides functionalities to convert Java objects to matching JSON
constructs and vice versa. It uses instances of JsonParser and
JsonGenerator for implementing actual reading/writing of JSON.
ObjectMapper class inherits methods from java.lang.Object.
ObjectMapper Class Declaration
Following is the declaration for org.codehaus.jackson.map.ObjectMapper class −public class ObjectMapper extends ObjectCodec implements Versioned
ObjectMapper Nested Classes
S.No. | Class & Description |
---|---|
1 | static class ObjectMapper.DefaultTypeResolverBuilder Customized TypeResolverBuilder that provides type resolver builders used with so-called "default typing" (see enableDefaultTyping() for details). |
2 | static class ObjectMapper.DefaultTyping Enumeration used with enableDefaultTyping() to specify what kind of types (classes) default typing should be used for. |
ObjectMapper Class Constructors
S.No. | Constructor & Description |
---|---|
1 | ObjectMapper() It is the default constructor, which constructs the default JsonFactory as necessary. Use StdSerializerProvider as its SerializerProvider, and BeanSerializerFactory as its SerializerFactory. |
2 | ObjectMapper(JsonFactory jf) Construct mapper that uses specified JsonFactory for constructing necessary JsonParsers and/or JsonGenerators. |
3 | ObjectMapper(JsonFactory jf, SerializerProvider sp, DeserializerProvider dp) |
4 | ObjectMapper(JsonFactory jf, SerializerProvider sp, DeserializerProvider dp, SerializationConfig sconfig, DeserializationConfig dconfig) |
5 | ObjectMapper(SerializerFactory sf)
Deprecated. Use other constructors instead; note that you can set the serializer factory with − setSerializerFactory(org.codehaus.jackson.map.SerializerFactory) |
ObjectMapper Methods
S.No. | Method & Description |
---|---|
1 | protected void _configAndWriteValue(JsonGenerator jgen, Object value) Method called to configure the generator as necessary and then call write functionality. |
2 | protected void _configAndWriteValue(JsonGenerator jgen, Object value, Class<?> viewClass) |
3 | protected Object _convert(Object fromValue, JavaType toValueType) |
4 | protected DeserializationContext _createDeserializationContext(JsonParser jp, DeserializationConfig cfg) |
5 | protected PrettyPrinter _defaultPrettyPrinter() Helper method that should return default pretty-printer to use for generators constructed by this mapper, when instructed to use default pretty printer. |
6 | protected JsonDeserializer<Object> _findRootDeserializer(DeserializationConfig cfg, JavaType valueType) Method called to locate deserializer for the passed root-level value. |
7 | protected JsonToken _initForReading(JsonParser jp) Method called to ensure that given parser is ready for reading content for data binding. |
8 | protected Object _readMapAndClose(JsonParser jp, JavaType valueType) |
9 | protected Object _readValue(DeserializationConfig cfg, JsonParser jp, JavaType valueType) Actual implementation of value reading + binding operation. |
10 | protected Object _unwrapAndDeserialize(JsonParser jp, JavaType rootType, DeserializationContext ctxt, JsonDeserializer<Object> deser) |
11 | boolean canDeserialize(JavaType type) Method that can be called to check whether mapper thinks it could deserialize an Object of given type. |
12 | boolean canSerialize(Class<?> type) Method that can be called to check whether mapper thinks it could serialize an instance of given Class. |
13 | ObjectMapper configure(DeserializationConfig.Feature f, boolean state) Method for changing state of an on/off deserialization feature for this object mapper. |
14 | ObjectMapper configure(JsonGenerator.Feature f, boolean state) Method for changing state of an on/off JsonGenerator feature for JsonFactory instance this object mapper uses. |
15 | ObjectMapper configure(JsonParser.Feature f, boolean state) Method for changing state of an on/off JsonParser feature for JsonFactory instance this object mapper uses. |
16 | ObjectMapper configure(SerializationConfig.Feature f, boolean state) Method for changing state of an on/off serialization feature for this object mapper. |
17 | JavaType constructType(Type t) Convenience method for constructing JavaType out of given type (typically java.lang.Class), but without explicit context. |
18 | <T> T convertValue(Object fromValue, Class<T> toValueType) Convenience method for doing two-step conversion from given value, into instance of given value type. |
19 | <T> T convertValue(Object fromValue, JavaType toValueType) |
20 | <T> T convertValue(Object fromValue, TypeReference toValueTypeRef) |
21 | DeserializationConfig copyDeserializationConfig() Method that creates a copy of the shared default DeserializationConfig object that defines configuration settings for deserialization. |
22 | SerializationConfig copySerializationConfig() Method that creates a copy of the shared default SerializationConfig object that defines configuration settings for serialization. |
23 | ArrayNode createArrayNode() Note − return type is co-variant, as basic ObjectCodec abstraction cannot refer to concrete node types (as it is a part of core package, whereas impls are part of mapper package). |
24 | ObjectNode createObjectNode() Note − return type is co-variant, as basic ObjectCodec abstraction cannot refer to concrete node types (as it is part of core package, whereas impls are part of mapper package) |
25 | ObjectWriter defaultPrettyPrintingWriter() Deprecated. Since 1.9, use writerWithDefaultPrettyPrinter() instead. |
26 | ObjectMapper disable(DeserializationConfig.Feature... f) Method for enabling specified DeserializationConfig features. |
27 | ObjectMapper disable(SerializationConfig.Feature... f) Method for enabling specified DeserializationConfig features. |
28 | ObjectMapper disableDefaultTyping() Method for disabling automatic inclusion of type information; if so, only explicitly annotated types (ones with JsonTypeInfo) has additional embedded type information. |
29 | ObjectMapper enable(DeserializationConfig.Feature... f) Method for enabling specified DeserializationConfig features. |
30 | ObjectMapper enable(SerializationConfig.Feature... f) Method for enabling specified DeserializationConfig features. |
31 | ObjectMapper enableDefaultTyping() Convenience method that is equivalent to calling. |
32 | ObjectMapper enableDefaultTyping(ObjectMapper.DefaultTyping dti) Convenience method that is equivalent to calling. |
33 | ObjectMapper enableDefaultTyping(ObjectMapper.DefaultTyping applicability, JsonTypeInfo.As includeAs) Method for enabling automatic inclusion of type information, needed for proper deserialization of polymorphic types (unless types are annotated with JsonTypeInfo). |
34 | ObjectMapper enableDefaultTypingAsProperty(ObjectMapper.DefaultTyping applicability, String propertyName) Method for enabling automatic inclusion of type information -- needed for proper deserialization of polymorphic types (unless types have been annotated with JsonTypeInfo) -- using "As.PROPERTY" inclusion mechanism and specified property name to use for inclusion (default being "@class" since default type information always uses class name as type identifier) |
35 | ObjectWriter filteredWriter(FilterProvider filterProvider) Deprecated. Since 1.9, use writer(FilterProvider) instead. |
36 | JsonSchema generateJsonSchema(Class<?> t) Generate Json-schema instance for specified class. |
37 | JsonSchema generateJsonSchema(Class<?> t, SerializationConfig cfg) Generate Json-schema instance for specified class, using specific serialization configuration |
38 | DeserializationConfig getDeserializationConfig() Method that returns the shared default DeserializationConfig object that defines configuration settings for deserialization. |
39 | DeserializerProvider getDeserializerProvider() |
40 | JsonFactory getJsonFactory() Method that can be used to get hold of JsonFactory that this mapper uses if it needs to construct JsonParsers and/or JsonGenerators. |
41 | JsonNodeFactory getNodeFactory() Method that can be used to get hold of JsonNodeFactory that this mapper will use when directly constructing root JsonNode instances for Trees. |
42 | SerializationConfig getSerializationConfig() Method that returns the shared default SerializationConfig object that defines configuration settings for serialization. |
43 | SerializerProvider getSerializerProvider() |
44 | SubtypeResolver getSubtypeResolver() Method for accessing subtype resolver in use. |
45 | TypeFactory getTypeFactory() Accessor for getting currently configured TypeFactory instance. |
46 | VisibilityChecker<?> getVisibilityChecker() Method for accessing currently configured visibility checker; object used for determining whether given property element (method, field, constructor) can be auto-detected or not. |
47 | boolean isEnabled(DeserializationConfig.Feature f) |
48 | boolean isEnabled(JsonGenerator.Feature f) |
49 | boolean isEnabled(JsonParser.Feature f) |
50 | boolean isEnabled(SerializationConfig.Feature f) |
51 | ObjectWriter prettyPrintingWriter(PrettyPrinter pp) |
52 | ObjectReader reader() Factory method for constructing ObjectReader with default settings. |
53 | ObjectReader reader(Class<?> type) Factory method for constructing ObjectReader that reads or update instances of specified type. |
54 | ObjectReader reader(FormatSchema schema) Factory method for constructing ObjectReader that will pass specific schema object to JsonParser used for reading content. |
55 | ObjectReader reader(InjectableValues injectableValues) Factory method for constructing ObjectReader that will use specified injectable values. |
56 | ObjectReader reader(JavaType type) Factory method for constructing ObjectReader that will read or update instances of specified type. |
57 | ObjectReader reader(JsonNodeFactory f) Factory method for constructing ObjectReader that will use specified JsonNodeFactory for constructing JSON trees. |
58 | ObjectReader reader(TypeReference<?> type) Factory method for constructing ObjectReader that will read or update instances of specified type. |
59 | ObjectReader readerForUpdating(Object valueToUpdate) Factory method for constructing ObjectReader that will update given Object (usually Bean, but can be a Collection or Map as well, but NOT an array) with JSON data. |
60 | JsonNode readTree(byte[] content) Method to deserialize JSON content as tree expressed using set of JsonNode instances. |
61 | JsonNode readTree(File file) Method to deserialize JSON content as tree expressed using set of JsonNode instances. |
62 | JsonNode readTree(InputStream in) Method to deserialize JSON content as tree expressed using set of JsonNode instances. |
63 | JsonNode readTree(JsonParser jp) Method to deserialize JSON content as tree expressed using set of JsonNode instances. |
64 | JsonNode readTree(JsonParser jp, DeserializationConfig cfg) Method to deserialize JSON content as tree expressed using set of JsonNode instances. |
65 | JsonNode readTree(Reader r) Method to deserialize JSON content as tree expressed using set of JsonNode instances. |
66 | JsonNode readTree(String content) Method to deserialize JSON content as tree expressed using set of JsonNode instances. |
67 | JsonNode readTree(URL source) Method to deserialize JSON content as tree expressed using set of JsonNode instances. |
68 | <T> T readValue(byte[] src, Class<T> valueType) |
69 | <T> T readValue(byte[] src, int offset, int len, Class<T> valueType) |
70 | <T> T readValue(byte[] src, int offset, int len, JavaType valueType) |
71 | <T> T readValue(byte[] src, int offset, int len, TypeReference valueTypeRef) |
72 | <T> T readValue(byte[] src, JavaType valueType) |
73 | <T> T readValue(byte[] src, TypeReference valueTypeRef) |
74 | <T> T readValue(File src, Class<T> valueType) |
75 | <T> T readValue(File src, JavaType valueType) |
76 | <T> T readValue(File src, TypeReference valueTypeRef) |
77 | <T> T readValue(InputStream src, Class<T> valueType) |
78 | <T> T readValue(InputStream src, JavaType valueType) |
79 | <T> T readValue(InputStream src, TypeReference valueTypeRef) |
80 | <T> T readValue(JsonNode root, Class<T> valueType) Convenience method for converting results from given JSON tree into given value type. |
81 | <T> T readValue(JsonNode root, JavaType valueType) Convenience method for converting results from given JSON tree into given value type. |
82 | <T> T readValue(JsonNode root, TypeReference valueTypeRef) Convenience method for converting results from given JSON tree into given value type. |
83 | <T> T readValue(JsonParser jp, 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). |
84 | <T> T readValue(JsonParser jp, Class<T> valueType, DeserializationConfig cfg) 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). |
85 | <T> T readValue(JsonParser jp, JavaType valueType) Method to deserialize JSON content into a Java type, reference to which is passed as argument. |
86 | <T> T readValue(JsonParser jp, JavaType valueType, DeserializationConfig cfg) Method to deserialize JSON content into a Java type, reference to which is passed as argument. |
87 | <T> T readValue(JsonParser jp, TypeReference<?> valueTypeRef) Method to deserialize JSON content into a Java type, reference to which is passed as argument. |
88 | <T> T readValue(JsonParser jp, TypeReference<?> valueTypeRef, DeserializationConfig cfg) Method to deserialize JSON content into a Java type, reference to which is passed as argument. |
89 | <T> T readValue(Reader src, Class<T> valueType) |
90 | <T> T readValue(Reader src, JavaType valueType) |
91 | <T> T readValue(Reader src, TypeReference valueTypeRef) |
92 | <T> T readValue(String content, Class<T> valueType) |
93 | <T> T readValue(String content, JavaType valueType) |
94 | <T> T readValue(String content, TypeReference valueTypeRef) |
95 | <T> T readValue(URL src, Class<T> valueType) |
96 | <T> T readValue(URL src, JavaType valueType) |
97 | <T> T readValue(URL src, TypeReference valueTypeRef) |
98 | <T> MappingIterator<T> readValues(JsonParser jp, Class<T> valueType) Method for reading sequence of Objects from parser stream. |
99 | <T> MappingIterator<T> readValues(JsonParser jp, JavaType valueType) Method for reading sequence of Objects from parser stream. |
100 | <T> MappingIterator<T> readValues(JsonParser jp, TypeReference<?> valueTypeRef) Method for reading sequence of Objects from parser stream. |
101 | void registerModule(Module module) Method for registering a module that can extend functionality provided by this mapper; for example, by adding providers for custom serializers and deserializers. |
102 | void registerSubtypes(Class<?>... classes) Method for registering specified class as a subtype, so that typename-based resolution can link supertypes to subtypes (as an alternative to using annotations). |
103 | void registerSubtypes(NamedType... types) Method for registering specified class as a subtype, so that typename-based resolution can link supertypes to subtypes (as an alternative to using annotations). |
104 | ObjectReader schemaBasedReader(FormatSchema schema) |
105 | ObjectWriter schemaBasedWriter(FormatSchema schema) |
106 | ObjectMapper setAnnotationIntrospector(AnnotationIntrospector ai) Method for changing AnnotationIntrospector used by this mapper instance for both serialization and deserialization. |
107 | void setDateFormat(DateFormat dateFormat) Method for configuring the default DateFormat to use when serializing time values as Strings, and deserializing from JSON Strings. |
108 | ObjectMapper setDefaultTyping(TypeResolverBuilder<?> typer) Method for enabling automatic inclusion of type information, using specified handler object for determining which types this affects, as well as details of how information is embedded. |
109 | ObjectMapper setDeserializationConfig(DeserializationConfig cfg) Method for replacing the shared default deserialization configuration object. |
110 | ObjectMapper setDeserializerProvider(DeserializerProvider p) Method for setting specific DeserializerProvider to use for handling the caching of JsonDeserializer instances. |
111 | void setFilters(FilterProvider filterProvider) |
112 | void setHandlerInstantiator(HandlerInstantiator hi) Method for configuring HandlerInstantiator to use for creating instances of handlers (such as serializers, deserializers, type and type id resolvers), given a class. |
113 | ObjectMapper setInjectableValues(InjectableValues injectableValues) |
114 | ObjectMapper setNodeFactory(JsonNodeFactory f) Method for specifying JsonNodeFactory to use for constructing root level tree nodes (via method createObjectNode() |
115 | ObjectMapper setPropertyNamingStrategy(PropertyNamingStrategy s) Method for setting custom property naming strategy to use. |
116 | ObjectMapper setSerializationConfig(SerializationConfig cfg) Method for replacing the shared default serialization configuration object. |
117 | ObjectMapper setSerializationInclusion(JsonSerialize.Inclusion incl) Method for setting default POJO property inclusion strategy for serialization. |
118 | ObjectMapper setSerializerFactory(SerializerFactory f) Method for setting specific SerializerFactory to use for constructing (bean) serializers. |
119 | ObjectMapper setSerializerProvider(SerializerProvider p) Method for setting specific SerializerProvider to use for handling caching of JsonSerializer instances. |
120 | void setSubtypeResolver(SubtypeResolver r) Method for setting custom subtype resolver to use. |
121 | ObjectMapper setTypeFactory(TypeFactory f) Method that can be used to override TypeFactory instance used by this mapper. |
122 | ObjectMapper setVisibility(JsonMethod forMethod, JsonAutoDetect.Visibility visibility) Convenience method that allows changing configuration for underlying VisibilityCheckers, to change details of what kinds of properties are auto-detected. |
123 | void setVisibilityChecker(VisibilityChecker<?> vc) Method for setting currently configured visibility checker; object used to determine whether given property element (method, field, constructor) can be auto-detected or not. |
125 | JsonParser treeAsTokens(JsonNode n) Method for constructing a JsonParser out of JSON tree representation. |
126 | <T> T treeToValue(JsonNode n, Class<T> valueType) Convenience conversion method that binds data provided the JSON tree contains a specific value (usually bean) type. |
127 | ObjectWriter typedWriter(Class<?> rootType) Deprecated. Since 1.9, use writerWithType(Class) instead. |
128 | ObjectWriter typedWriter(JavaType rootType) Deprecated. Since 1.9, use writerWithType(JavaType) instead. |
129 | ObjectWriter typedWriter(TypeReference<?> rootType) Deprecated. Since 1.9, use writerWithType(TypeReference) instead. |
130 | ObjectReader updatingReader(Object valueToUpdate) Deprecated. Since 1.9, use readerForUpdating(java.lang.Object) instead. |
131 | <T extends JsonNode> T valueToTree(Object fromValue) Reverse of treeToValue(org.codehaus.jackson.JsonNode, java.lang.Class); given a value (usually bean), constructs equivalent JSON Tree representation. |
132 | Version version() Method that will return version information stored and reads from jar that contains this class. |
133 | ObjectWriter viewWriter(Class<?> serializationView) Deprecated. Since 1.9, use writerWithView(Class) instead. |
134 | ObjectMapper withModule(Module module) Fluent-style alternative to registerModule(org.codehaus.jackson.map.Module); |
135 | ObjectWriter writer() Convenience method for constructing ObjectWriter with default settings. |
136 | ObjectWriter writer(DateFormat df) Factory method for constructing ObjectWriter that serializes objects using specified DateFormat; or, if null passed, using timestamp (64-bit number. |
137 | ObjectWriter writer(FilterProvider filterProvider) Factory method for constructing ObjectWriter that serializes objects using specified filter provider. |
138 | ObjectWriter writer(FormatSchema schema) Factory method for constructing ObjectWriter that passes specific schema object to JsonGenerator used for writing content. |
139 | ObjectWriter writer(PrettyPrinter pp) Factory method for constructing ObjectWriter that serializes objects using specified pretty printer for indentation (or if null, no pretty printer) |
140 | ObjectWriter writerWithDefaultPrettyPrinter() Factory method for constructing ObjectWriter that serializes objects using the default pretty printer for indentation. |
141 | ObjectWriter writerWithType(Class<?> rootType) Factory method for constructing ObjectWriter that serializes objects using specified root type, instead of actual runtime type of value. |
142 | ObjectWriter writerWithType(JavaType rootType) Factory method for constructing ObjectWriter that serializes objects using specified root type, instead of actual runtime type of value. |
143 | ObjectWriter writerWithType(TypeReference<?> rootType) Factory method for constructing ObjectWriter that serializes objects using specified root type, instead of actual runtime type of value. |
144 | ObjectWriter writerWithView(Class<?> serializationView) Factory method for constructing ObjectWriter that serializes objects using specified JSON View (filter). |
145 | void writeTree(JsonGenerator jgen, JsonNode rootNode) Method to serialize given JSON Tree, using generator provided. |
146 | void writeTree(JsonGenerator jgen, JsonNode rootNode, SerializationConfig cfg) Method to serialize given Json Tree, using generator provided. |
147 | void writeValue(File resultFile, Object value) Method that can be used to serialize any Java value as JSON output, written to File provided. |
148 | void writeValue(JsonGenerator jgen, Object value) Method that can be used to serialize any Java value as JSON output, using provided JsonGenerator. |
149 | void writeValue(JsonGenerator jgen, Object value, SerializationConfig config) Method that can be used to serialize any Java value as JSON output, using provided JsonGenerator, configured as per passed configuration object. |
150 | void writeValue(OutputStream out, Object value) Method that can be used to serialize any Java value as JSON output, using output stream provided (using encoding JsonEncoding.UTF8). |
151 | void writeValue(Writer w, Object value) Method that can be used to serialize any Java value as JSON output, using Writer provided. |
152 | byte[] writeValueAsBytes(Object value) Method that used to serialize any Java value as a byte array. |
153 | String writeValueAsString(Object value) Method that can be used to serialize any Java value as a String. |
ObjectMapper Example
Create the following Java program using any editor of your choice and save it in the folder C:/> Jackson_WORKSPACEFile: JacksonTester.java
import java.io.IOException; import org.codehaus.jackson.JsonParseException; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.SerializationConfig; 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); mapper.enable(SerializationConfig.Feature.INDENT_OUTPUT); jsonString = mapper.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+ " ]"; } }
Verify the Result
Compile the classes using javac compiler as follows −C:\Jackson_WORKSPACE>javac JacksonTester.javaNow execute the jacksonTester to see the result.
C:\Jackson_WORKSPACE>java JacksonTesterVerify the output −
Student [ name: Mahesh, age: 21 ] { "name" : "Mahesh", "age" : 21
No comments:
Post a Comment