1 package com.fasterxml.jackson.databind;
2
3 import java.io.*;
4 import java.lang.reflect.Type;
5 import java.net.URL;
6 import java.security.AccessController;
7 import java.security.PrivilegedAction;
8 import java.text.DateFormat;
9 import java.util.*;
10 import java.util.concurrent.ConcurrentHashMap;
11 import java.util.concurrent.atomic.AtomicReference;
12
13 import com.fasterxml.jackson.annotation.*;
14 import com.fasterxml.jackson.core.*;
15 import com.fasterxml.jackson.core.io.CharacterEscapes;
16 import com.fasterxml.jackson.core.io.SegmentedStringWriter;
17 import com.fasterxml.jackson.core.type.ResolvedType;
18 import com.fasterxml.jackson.core.type.TypeReference;
19 import com.fasterxml.jackson.core.util.*;
20 import com.fasterxml.jackson.databind.cfg.*;
21 import com.fasterxml.jackson.databind.deser.*;
22 import com.fasterxml.jackson.databind.exc.MismatchedInputException;
23 import com.fasterxml.jackson.databind.introspect.*;
24 import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonFormatVisitorWrapper;
25 import com.fasterxml.jackson.databind.jsontype.*;
26 import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
27 import com.fasterxml.jackson.databind.jsontype.impl.StdSubtypeResolver;
28 import com.fasterxml.jackson.databind.jsontype.impl.StdTypeResolverBuilder;
29 import com.fasterxml.jackson.databind.node.*;
30 import com.fasterxml.jackson.databind.ser.*;
31 import com.fasterxml.jackson.databind.type.*;
32 import com.fasterxml.jackson.databind.util.ClassUtil;
33 import com.fasterxml.jackson.databind.util.RootNameLookup;
34 import com.fasterxml.jackson.databind.util.StdDateFormat;
35 import com.fasterxml.jackson.databind.util.TokenBuffer;
36
37 /**
38 * ObjectMapper provides functionality for reading and writing JSON,
39 * either to and from basic POJOs (Plain Old Java Objects), or to and from
40 * a general-purpose JSON Tree Model ({@link JsonNode}), as well as
41 * related functionality for performing conversions.
42 * It is also highly customizable to work both with different styles of JSON
43 * content, and to support more advanced Object concepts such as
44 * polymorphism and Object identity.
45 * <code>ObjectMapper</code> also acts as a factory for more advanced {@link ObjectReader}
46 * and {@link ObjectWriter} classes.
47 * Mapper (and {@link ObjectReader}s, {@link ObjectWriter}s it constructs) will
48 * use instances of {@link JsonParser} and {@link JsonGenerator}
49 * for implementing actual reading/writing of JSON.
50 * Note that although most read and write methods are exposed through this class,
51 * some of the functionality is only exposed via {@link ObjectReader} and
52 * {@link ObjectWriter}: specifically, reading/writing of longer sequences of
53 * values is only available through {@link ObjectReader#readValues(InputStream)}
54 * and {@link ObjectWriter#writeValues(OutputStream)}.
55 *<p>
56 Simplest usage is of form:
57 <pre>
58 final ObjectMapper mapper = new ObjectMapper(); // can use static singleton, inject: just make sure to reuse!
59 MyValue value = new MyValue();
60 // ... and configure
61 File newState = new File("my-stuff.json");
62 mapper.writeValue(newState, value); // writes JSON serialization of MyValue instance
63 // or, read
64 MyValue older = mapper.readValue(new File("my-older-stuff.json"), MyValue.class);
65
66 // Or if you prefer JSON Tree representation:
67 JsonNode root = mapper.readTree(newState);
68 // and find values by, for example, using a {@link com.fasterxml.jackson.core.JsonPointer} expression:
69 int age = root.at("/personal/age").getValueAsInt();
70 </pre>
71 *<p>
72 * The main conversion API is defined in {@link ObjectCodec}, so that
73 * implementation details of this class need not be exposed to
74 * streaming parser and generator classes. Usage via {@link ObjectCodec} is,
75 * however, usually only for cases where dependency to {@link ObjectMapper} is
76 * either not possible (from Streaming API), or undesireable (when only relying
77 * on Streaming API).
78 *<p>
79 * Mapper instances are fully thread-safe provided that ALL configuration of the
80 * instance occurs before ANY read or write calls. If configuration of a mapper instance
81 * is modified after first usage, changes may or may not take effect, and configuration
82 * calls themselves may fail.
83 * If you need to use different configuration, you have two main possibilities:
84 *<ul>
85 * <li>Construct and use {@link ObjectReader} for reading, {@link ObjectWriter} for writing.
86 * Both types are fully immutable and you can freely create new instances with different
87 * configuration using either factory methods of {@link ObjectMapper}, or readers/writers
88 * themselves. Construction of new {@link ObjectReader}s and {@link ObjectWriter}s is
89 * a very light-weight operation so it is usually appropriate to create these on per-call
90 * basis, as needed, for configuring things like optional indentation of JSON.
91 * </li>
92 * <li>If the specific kind of configurability is not available via {@link ObjectReader} and
93 * {@link ObjectWriter}, you may need to use multiple {@link ObjectMapper} instead (for example:
94 * you cannot change mix-in annotations on-the-fly; or, set of custom (de)serializers).
95 * To help with this usage, you may want to use method {@link #copy()} which creates a clone
96 * of the mapper with specific configuration, and allows configuration of the copied instance
97 * before it gets used. Note that {@link #copy} operation is as expensive as constructing
98 * a new {@link ObjectMapper} instance: if possible, you should still pool and reuse mappers
99 * if you intend to use them for multiple operations.
100 * </li>
101 * </ul>
102 *<p>
103 * Note on caching: root-level deserializers are always cached, and accessed
104 * using full (generics-aware) type information. This is different from
105 * caching of referenced types, which is more limited and is done only
106 * for a subset of all deserializer types. The main reason for difference
107 * is that at root-level there is no incoming reference (and hence no
108 * referencing property, no referral information or annotations to
109 * produce differing deserializers), and that the performance impact
110 * greatest at root level (since it'll essentially cache the full
111 * graph of deserializers involved).
112 *<p>
113 * Notes on security: use "default typing" feature (see {@link #enableDefaultTyping()})
114 * is a potential security risk, if used with untrusted content (content generated by
115 * untrusted external parties). If so, you may want to construct a custom
116 * {@link TypeResolverBuilder} implementation to limit possible types to instantiate,
117 * (using {@link #setDefaultTyping}).
118 */
119 public class ObjectMapper
120 extends ObjectCodec
121 implements Versioned,
122 java.io.Serializable // as of 2.1
123 {
124 private static final long serialVersionUID = 2L; // as of 2.9
125
126 /*
127 /**********************************************************
128 /* Helper classes, enums
129 /**********************************************************
130 */
131
132 /**
133 * Enumeration used with {@link ObjectMapper#activateDefaultTyping(PolymorphicTypeValidator)}
134 * to specify what kind of types (classes) default typing should
135 * be used for. It will only be used if no explicit type information
136 * is found, but this enumeration further limits subset of those types.
137 *<p>
138 * Since 2.4 there are special exceptions for JSON Tree model
139 * types (sub-types of {@link TreeNode}: default typing is never
140 * applied to them.
141 * Since 2.8(.4) additional checks are made to avoid attempts at default
142 * typing primitive-valued properties.
143 *<p>
144 * NOTE: use of Default Typing can be a potential security risk if incoming
145 * content comes from untrusted sources, and it is recommended that this
146 * is either not done, or, if enabled, make sure to {@code activateDefaultTyping(...)}
147 * methods that take {@link PolymorphicTypeValidator} that limits applicability
148 * to known trusted types.
149 */
150 public enum DefaultTyping {
151 /**
152 * This value means that only properties that have
153 * {@link java.lang.Object} as declared type (including
154 * generic types without explicit type) will use default
155 * typing.
156 */
157 JAVA_LANG_OBJECT,
158
159 /**
160 * Value that means that default typing will be used for
161 * properties with declared type of {@link java.lang.Object}
162 * or an abstract type (abstract class or interface).
163 * Note that this does <b>not</b> include array types.
164 *<p>
165 * Since 2.4, this does NOT apply to {@link TreeNode} and its subtypes.
166 */
167 OBJECT_AND_NON_CONCRETE,
168
169 /**
170 * Value that means that default typing will be used for
171 * all types covered by {@link #OBJECT_AND_NON_CONCRETE}
172 * plus all array types for them.
173 *<p>
174 * Since 2.4, this does NOT apply to {@link TreeNode} and its subtypes.
175 */
176 NON_CONCRETE_AND_ARRAYS,
177
178 /**
179 * Value that means that default typing will be used for
180 * all non-final types, with exception of small number of
181 * "natural" types (String, Boolean, Integer, Double), which
182 * can be correctly inferred from JSON; as well as for
183 * all arrays of non-final types.
184 *<p>
185 * Since 2.4, this does NOT apply to {@link TreeNode} and its subtypes.
186 */
187 NON_FINAL,
188
189 /**
190 * Value that means that default typing will be used for
191 * all types, with exception of small number of
192 * "natural" types (String, Boolean, Integer, Double) that
193 * can be correctly inferred from JSON, and primitives (which
194 * can not be polymorphic either). Typing is also enabled for
195 * all array types.
196 *<p>
197 * Note that this is rarely the option you should use as it results
198 * in adding type information in many places where it should not be needed:
199 * make sure you understand its behavior.
200 * The only known use case for this setting is for serialization
201 * when passing instances of final class, and base type is not
202 * separately specified.
203 *
204 * @since 2.10
205 */
206 EVERYTHING
207 }
208
209 /**
210 * Customized {@link TypeResolverBuilder} that provides type resolver builders
211 * used with so-called "default typing"
212 * (see {@link ObjectMapper#activateDefaultTyping(PolymorphicTypeValidator)} for details).
213 *<p>
214 * Type resolver construction is based on configuration: implementation takes care
215 * of only providing builders in cases where type information should be applied.
216 * This is important since build calls may be sent for any and all types, and
217 * type information should NOT be applied to all of them.
218 */
219 public static class DefaultTypeResolverBuilder
220 extends StdTypeResolverBuilder
221 implements java.io.Serializable
222 {
223 private static final long serialVersionUID = 1L;
224
225 /**
226 * Definition of what types is this default typer valid for.
227 */
228 protected final DefaultTyping _appliesFor;
229
230 /**
231 * {@link PolymorphicTypeValidator} top use for validating that the subtypes
232 * resolved are valid for use (usually to protect against possible
233 * security issues)
234 *
235 * @since 2.10
236 */
237 protected final PolymorphicTypeValidator _subtypeValidator;
238
239 /**
240 * @deprecated Since 2.10
241 */
242 @Deprecated // since 2.10
243 public DefaultTypeResolverBuilder(DefaultTyping t) {
244 this(t, LaissezFaireSubTypeValidator.instance);
245 }
246
247 /**
248 * @since 2.10
249 */
250 public DefaultTypeResolverBuilder(DefaultTyping t, PolymorphicTypeValidator ptv) {
251 _appliesFor = _requireNonNull(t, "Can not pass `null` DefaultTyping");
252 _subtypeValidator = _requireNonNull(ptv, "Can not pass `null` PolymorphicTypeValidator");
253 }
254
255 // 20-Jan-2020: as per [databind#2599] Objects.requireNonNull() from JDK7 not in all Android so
256 private static <T> T _requireNonNull(T value, String msg) {
257 // Replacement for: return Objects.requireNonNull(t, msg);
258 if (value == null) {
259 throw new NullPointerException(msg);
260 }
261 return value;
262 }
263
264 /**
265 * @since 2.10
266 */
267 public static DefaultTypeResolverBuilder construct(DefaultTyping t,
268 PolymorphicTypeValidator ptv) {
269 return new DefaultTypeResolverBuilder(t, ptv);
270 }
271
272 @Override // since 2.10
273 public PolymorphicTypeValidator subTypeValidator(MapperConfig<?> config) {
274 return _subtypeValidator;
275 }
276
277 @Override
278 public TypeDeserializer buildTypeDeserializer(DeserializationConfig config,
279 JavaType baseType, Collection<NamedType> subtypes)
280 {
281 return useForType(baseType) ? super.buildTypeDeserializer(config, baseType, subtypes) : null;
282 }
283
284 @Override
285 public TypeSerializer buildTypeSerializer(SerializationConfig config,
286 JavaType baseType, Collection<NamedType> subtypes)
287 {
288 return useForType(baseType) ? super.buildTypeSerializer(config, baseType, subtypes) : null;
289 }
290
291 /**
292 * Method called to check if the default type handler should be
293 * used for given type.
294 * Note: "natural types" (String, Boolean, Integer, Double) will never
295 * use typing; that is both due to them being concrete and final,
296 * and since actual serializers and deserializers will also ignore any
297 * attempts to enforce typing.
298 */
299 public boolean useForType(JavaType t)
300 {
301 // 03-Oct-2016, tatu: As per [databind#1395], need to skip
302 // primitive types too, regardless
303 if (t.isPrimitive()) {
304 return false;
305 }
306
307 switch (_appliesFor) {
308 case NON_CONCRETE_AND_ARRAYS:
309 while (t.isArrayType()) {
310 t = t.getContentType();
311 }
312 // fall through
313 case OBJECT_AND_NON_CONCRETE:
314 // 19-Apr-2016, tatu: ReferenceType like Optional also requires similar handling:
315 while (t.isReferenceType()) {
316 t = t.getReferencedType();
317 }
318 return t.isJavaLangObject()
319 || (!t.isConcrete()
320 // [databind#88] Should not apply to JSON tree models:
321 && !TreeNode.class.isAssignableFrom(t.getRawClass()));
322
323 case NON_FINAL:
324 while (t.isArrayType()) {
325 t = t.getContentType();
326 }
327 // 19-Apr-2016, tatu: ReferenceType like Optional also requires similar handling:
328 while (t.isReferenceType()) {
329 t = t.getReferencedType();
330 }
331 // [databind#88] Should not apply to JSON tree models:
332 return !t.isFinal() && !TreeNode.class.isAssignableFrom(t.getRawClass());
333 case EVERYTHING:
334 // So, excluding primitives (handled earlier) and "Natural types" (handled
335 // before this method is called), applied to everything
336 return true;
337 default:
338 case JAVA_LANG_OBJECT:
339 return t.isJavaLangObject();
340 }
341 }
342 }
343
344 /*
345 /**********************************************************
346 /* Internal constants, singletons
347 /**********************************************************
348 */
349
350 // 16-May-2009, tatu: Ditto ^^^
351 protected final static AnnotationIntrospector DEFAULT_ANNOTATION_INTROSPECTOR = new JacksonAnnotationIntrospector();
352
353 /**
354 * Base settings contain defaults used for all {@link ObjectMapper}
355 * instances.
356 */
357 protected final static BaseSettings DEFAULT_BASE = new BaseSettings(
358 null, // cannot share global ClassIntrospector any more (2.5+)
359 DEFAULT_ANNOTATION_INTROSPECTOR,
360 null, TypeFactory.defaultInstance(),
361 null, StdDateFormat.instance, null,
362 Locale.getDefault(),
363 null, // to indicate "use Jackson default TimeZone" (UTC since Jackson 2.7)
364 Base64Variants.getDefaultVariant(),
365 // Only for 2.x; 3.x will use more restrictive default
366 LaissezFaireSubTypeValidator.instance
367 );
368
369 /*
370 /**********************************************************
371 /* Configuration settings, shared
372 /**********************************************************
373 */
374
375 /**
376 * Factory used to create {@link JsonParser} and {@link JsonGenerator}
377 * instances as necessary.
378 */
379 protected final JsonFactory _jsonFactory;
380
381 /**
382 * Specific factory used for creating {@link JavaType} instances;
383 * needed to allow modules to add more custom type handling
384 * (mostly to support types of non-Java JVM languages)
385 */
386 protected TypeFactory _typeFactory;
387
388 /**
389 * Provider for values to inject in deserialized POJOs.
390 */
391 protected InjectableValues _injectableValues;
392
393 /**
394 * Thing used for registering sub-types, resolving them to
395 * super/sub-types as needed.
396 */
397 protected SubtypeResolver _subtypeResolver;
398
399 /**
400 * Currently active per-type configuration overrides, accessed by
401 * declared type of property.
402 *
403 * @since 2.9
404 */
405 protected final ConfigOverrides _configOverrides;
406
407 /*
408 /**********************************************************
409 /* Configuration settings: mix-in annotations
410 /**********************************************************
411 */
412
413 /**
414 * Mapping that defines how to apply mix-in annotations: key is
415 * the type to received additional annotations, and value is the
416 * type that has annotations to "mix in".
417 *<p>
418 * Annotations associated with the value classes will be used to
419 * override annotations of the key class, associated with the
420 * same field or method. They can be further masked by sub-classes:
421 * you can think of it as injecting annotations between the target
422 * class and its sub-classes (or interfaces)
423 *
424 * @since 2.6 (earlier was a simple {@link java.util.Map}
425 */
426 protected SimpleMixInResolver _mixIns;
427
428 /*
429 /**********************************************************
430 /* Configuration settings, serialization
431 /**********************************************************
432 */
433
434 /**
435 * Configuration object that defines basic global
436 * settings for the serialization process
437 */
438 protected SerializationConfig _serializationConfig;
439
440 /**
441 * Object that manages access to serializers used for serialization,
442 * including caching.
443 * It is configured with {@link #_serializerFactory} to allow
444 * for constructing custom serializers.
445 *<p>
446 * Note: while serializers are only exposed {@link SerializerProvider},
447 * mappers and readers need to access additional API defined by
448 * {@link DefaultSerializerProvider}
449 */
450 protected DefaultSerializerProvider _serializerProvider;
451
452 /**
453 * Serializer factory used for constructing serializers.
454 */
455 protected SerializerFactory _serializerFactory;
456
457 /*
458 /**********************************************************
459 /* Configuration settings, deserialization
460 /**********************************************************
461 */
462
463 /**
464 * Configuration object that defines basic global
465 * settings for the serialization process
466 */
467 protected DeserializationConfig _deserializationConfig;
468
469 /**
470 * Blueprint context object; stored here to allow custom
471 * sub-classes. Contains references to objects needed for
472 * deserialization construction (cache, factory).
473 */
474 protected DefaultDeserializationContext _deserializationContext;
475
476 /*
477 /**********************************************************
478 /* Module-related
479 /**********************************************************
480 */
481
482 /**
483 * Set of module types (as per {@link Module#getTypeId()} that have been
484 * registered; kept track of iff {@link MapperFeature#IGNORE_DUPLICATE_MODULE_REGISTRATIONS}
485 * is enabled, so that duplicate registration calls can be ignored
486 * (to avoid adding same handlers multiple times, mostly).
487 *
488 * @since 2.5
489 */
490 protected Set<Object> _registeredModuleTypes;
491
492 /*
493 /**********************************************************
494 /* Caching
495 /**********************************************************
496 */
497
498 /* Note: handling of serializers and deserializers is not symmetric;
499 * and as a result, only root-level deserializers can be cached here.
500 * This is mostly because typing and resolution for deserializers is
501 * fully static; whereas it is quite dynamic for serialization.
502 */
503
504 /**
505 * We will use a separate main-level Map for keeping track
506 * of root-level deserializers. This is where most successful
507 * cache lookups get resolved.
508 * Map will contain resolvers for all kinds of types, including
509 * container types: this is different from the component cache
510 * which will only cache bean deserializers.
511 *<p>
512 * Given that we don't expect much concurrency for additions
513 * (should very quickly converge to zero after startup), let's
514 * explicitly define a low concurrency setting.
515 *<p>
516 * These may are either "raw" deserializers (when
517 * no type information is needed for base type), or type-wrapped
518 * deserializers (if it is needed)
519 */
520 final protected ConcurrentHashMap<JavaType, JsonDeserializer<Object>> _rootDeserializers
521 = new ConcurrentHashMap<JavaType, JsonDeserializer<Object>>(64, 0.6f, 2);
522
523 /*
524 /**********************************************************
525 /* Life-cycle: constructing instance
526 /**********************************************************
527 */
528
529 /**
530 * Default constructor, which will construct the default
531 * {@link JsonFactory} as necessary, use
532 * {@link SerializerProvider} as its
533 * {@link SerializerProvider}, and
534 * {@link BeanSerializerFactory} as its
535 * {@link SerializerFactory}.
536 * This means that it
537 * can serialize all standard JDK types, as well as regular
538 * Java Beans (based on method names and Jackson-specific annotations),
539 * but does not support JAXB annotations.
540 */
541 public ObjectMapper() {
542 this(null, null, null);
543 }
544
545 /**
546 * Constructs instance that uses specified {@link JsonFactory}
547 * for constructing necessary {@link JsonParser}s and/or
548 * {@link JsonGenerator}s.
549 */
550 public ObjectMapper(JsonFactory jf) {
551 this(jf, null, null);
552 }
553
554 /**
555 * Copy-constructor, mostly used to support {@link #copy}.
556 *
557 * @since 2.1
558 */
559 protected ObjectMapper(ObjectMapper src)
560 {
561 _jsonFactory = src._jsonFactory.copy();
562 _jsonFactory.setCodec(this);
563 _subtypeResolver = src._subtypeResolver.copy();
564 _typeFactory = src._typeFactory;
565 _injectableValues = src._injectableValues;
566 _configOverrides = src._configOverrides.copy();
567 _mixIns = src._mixIns.copy();
568
569 RootNameLookup rootNames = new RootNameLookup();
570 _serializationConfig = new SerializationConfig(src._serializationConfig,
571 _subtypeResolver, _mixIns, rootNames, _configOverrides);
572 _deserializationConfig = new DeserializationConfig(src._deserializationConfig,
573 _subtypeResolver, _mixIns, rootNames, _configOverrides);
574 _serializerProvider = src._serializerProvider.copy();
575 _deserializationContext = src._deserializationContext.copy();
576
577 // Default serializer factory is stateless, can just assign
578 _serializerFactory = src._serializerFactory;
579
580 // as per [databind#922], [databind#1078] make sure to copy registered modules as appropriate
581 Set<Object> reg = src._registeredModuleTypes;
582 if (reg == null) {
583 _registeredModuleTypes = null;
584 } else {
585 _registeredModuleTypes = new LinkedHashSet<Object>(reg);
586 }
587 }
588
589 /**
590 * Constructs instance that uses specified {@link JsonFactory}
591 * for constructing necessary {@link JsonParser}s and/or
592 * {@link JsonGenerator}s, and uses given providers for accessing
593 * serializers and deserializers.
594 *
595 * @param jf JsonFactory to use: if null, a new {@link MappingJsonFactory} will be constructed
596 * @param sp SerializerProvider to use: if null, a {@link SerializerProvider} will be constructed
597 * @param dc Blueprint deserialization context instance to use for creating
598 * actual context objects; if null, will construct standard
599 * {@link DeserializationContext}
600 */
601 public ObjectMapper(JsonFactory jf,
602 DefaultSerializerProvider sp, DefaultDeserializationContext dc)
603 {
604 /* 02-Mar-2009, tatu: Important: we MUST default to using
605 * the mapping factory, otherwise tree serialization will
606 * have problems with POJONodes.
607 * 03-Jan-2010, tatu: and obviously we also must pass 'this',
608 * to create actual linking.
609 */
610 if (jf == null) {
611 _jsonFactory = new MappingJsonFactory(this);
612 } else {
613 _jsonFactory = jf;
614 if (jf.getCodec() == null) { // as per [JACKSON-741]
615 _jsonFactory.setCodec(this);
616 }
617 }
618 _subtypeResolver = new StdSubtypeResolver();
619 RootNameLookup rootNames = new RootNameLookup();
620 // and default type factory is shared one
621 _typeFactory = TypeFactory.defaultInstance();
622
623 SimpleMixInResolver mixins = new SimpleMixInResolver(null);
624 _mixIns = mixins;
625 BaseSettings base = DEFAULT_BASE.withClassIntrospector(defaultClassIntrospector());
626 _configOverrides = new ConfigOverrides();
627 _serializationConfig = new SerializationConfig(base,
628 _subtypeResolver, mixins, rootNames, _configOverrides);
629 _deserializationConfig = new DeserializationConfig(base,
630 _subtypeResolver, mixins, rootNames, _configOverrides);
631
632 // Some overrides we may need
633 final boolean needOrder = _jsonFactory.requiresPropertyOrdering();
634 if (needOrder ^ _serializationConfig.isEnabled(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY)) {
635 configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, needOrder);
636 }
637
638 _serializerProvider = (sp == null) ? new DefaultSerializerProvider.Impl() : sp;
639 _deserializationContext = (dc == null) ?
640 new DefaultDeserializationContext.Impl(BeanDeserializerFactory.instance) : dc;
641
642 // Default serializer factory is stateless, can just assign
643 _serializerFactory = BeanSerializerFactory.instance;
644 }
645
646 /**
647 * Overridable helper method used to construct default {@link ClassIntrospector}
648 * to use.
649 *
650 * @since 2.5
651 */
652 protected ClassIntrospector defaultClassIntrospector() {
653 return new BasicClassIntrospector();
654 }
655
656 /*
657 /**********************************************************
658 /* Methods sub-classes MUST override
659 /**********************************************************
660 */
661
662 /**
663 * Method for creating a new {@link ObjectMapper} instance that
664 * has same initial configuration as this instance. Note that this
665 * also requires making a copy of the underlying {@link JsonFactory}
666 * instance.
667 *<p>
668 * Method is typically
669 * used when multiple, differently configured mappers are needed.
670 * Although configuration is shared, cached serializers and deserializers
671 * are NOT shared, which means that the new instance may be re-configured
672 * before use; meaning that it behaves the same way as if an instance
673 * was constructed from scratch.
674 *
675 * @since 2.1
676 */
677 public ObjectMapper copy() {
678 _checkInvalidCopy(ObjectMapper.class);
679 return new ObjectMapper(this);
680 }
681
682 /**
683 * @since 2.1
684 */
685 protected void _checkInvalidCopy(Class<?> exp)
686 {
687 if (getClass() != exp) {
688 // 10-Nov-2016, tatu: could almost use `ClassUtil.verifyMustOverride()` but not quite
689 throw new IllegalStateException("Failed copy(): "+getClass().getName()
690 +" (version: "+version()+") does not override copy(); it has to");
691 }
692 }
693
694 /*
695 /**********************************************************
696 /* Methods sub-classes MUST override if providing custom
697 /* ObjectReader/ObjectWriter implementations
698 /**********************************************************
699 */
700
701 /**
702 * Factory method sub-classes must override, to produce {@link ObjectReader}
703 * instances of proper sub-type
704 *
705 * @since 2.5
706 */
707 protected ObjectReader _newReader(DeserializationConfig config) {
708 return new ObjectReader(this, config);
709 }
710
711 /**
712 * Factory method sub-classes must override, to produce {@link ObjectReader}
713 * instances of proper sub-type
714 *
715 * @since 2.5
716 */
717 protected ObjectReader _newReader(DeserializationConfig config,
718 JavaType valueType, Object valueToUpdate,
719 FormatSchema schema, InjectableValues injectableValues) {
720 return new ObjectReader(this, config, valueType, valueToUpdate, schema, injectableValues);
721 }
722
723 /**
724 * Factory method sub-classes must override, to produce {@link ObjectWriter}
725 * instances of proper sub-type
726 *
727 * @since 2.5
728 */
729 protected ObjectWriter _newWriter(SerializationConfig config) {
730 return new ObjectWriter(this, config);
731 }
732
733 /**
734 * Factory method sub-classes must override, to produce {@link ObjectWriter}
735 * instances of proper sub-type
736 *
737 * @since 2.5
738 */
739 protected ObjectWriter _newWriter(SerializationConfig config, FormatSchema schema) {
740 return new ObjectWriter(this, config, schema);
741 }
742
743 /**
744 * Factory method sub-classes must override, to produce {@link ObjectWriter}
745 * instances of proper sub-type
746 *
747 * @since 2.5
748 */
749 protected ObjectWriter _newWriter(SerializationConfig config,
750 JavaType rootType, PrettyPrinter pp) {
751 return new ObjectWriter(this, config, rootType, pp);
752 }
753
754 /*
755 /**********************************************************
756 /* Versioned impl
757 /**********************************************************
758 */
759
760 /**
761 * Method that will return version information stored in and read from jar
762 * that contains this class.
763 */
764 @Override
765 public Version version() {
766 return com.fasterxml.jackson.databind.cfg.PackageVersion.VERSION;
767 }
768
769 /*
770 /**********************************************************
771 /* Module registration, discovery
772 /**********************************************************
773 */
774
775 /**
776 * Method for registering a module that can extend functionality
777 * provided by this mapper; for example, by adding providers for
778 * custom serializers and deserializers.
779 *
780 * @param module Module to register
781 */
782 public ObjectMapper registerModule(Module module)
783 {
784 _assertNotNull("module", module);
785 // Let's ensure we have access to name and version information,
786 // even if we do not have immediate use for either. This way we know
787 // that they will be available from beginning
788 String name = module.getModuleName();
789 if (name == null) {
790 throw new IllegalArgumentException("Module without defined name");
791 }
792 Version version = module.version();
793 if (version == null) {
794 throw new IllegalArgumentException("Module without defined version");
795 }
796
797 // [databind#2432]: Modules may depend on other modules; if so, register those first
798 for (Module dep : module.getDependencies()) {
799 registerModule(dep);
800 }
801
802 // then module itself
803 if (isEnabled(MapperFeature.IGNORE_DUPLICATE_MODULE_REGISTRATIONS)) {
804 Object typeId = module.getTypeId();
805 if (typeId != null) {
806 if (_registeredModuleTypes == null) {
807 // plus let's keep them in order too, easier to debug or expose
808 // in registration order if that matter
809 _registeredModuleTypes = new LinkedHashSet<Object>();
810 }
811 // try adding; if already had it, should skip
812 if (!_registeredModuleTypes.add(typeId)) {
813 return this;
814 }
815 }
816 }
817
818 // And then call registration
819 module.setupModule(new Module.SetupContext()
820 {
821 // // // Accessors
822
823 @Override
824 public Version getMapperVersion() {
825 return version();
826 }
827
828 @SuppressWarnings("unchecked")
829 @Override
830 public <C extends ObjectCodec> C getOwner() {
831 // why do we need the cast here?!?
832 return (C) ObjectMapper.this;
833 }
834
835 @Override
836 public TypeFactory getTypeFactory() {
837 return _typeFactory;
838 }
839
840 @Override
841 public boolean isEnabled(MapperFeature f) {
842 return ObjectMapper.this.isEnabled(f);
843 }
844
845 @Override
846 public boolean isEnabled(DeserializationFeature f) {
847 return ObjectMapper.this.isEnabled(f);
848 }
849
850 @Override
851 public boolean isEnabled(SerializationFeature f) {
852 return ObjectMapper.this.isEnabled(f);
853 }
854
855 @Override
856 public boolean isEnabled(JsonFactory.Feature f) {
857 return ObjectMapper.this.isEnabled(f);
858 }
859
860 @Override
861 public boolean isEnabled(JsonParser.Feature f) {
862 return ObjectMapper.this.isEnabled(f);
863 }
864
865 @Override
866 public boolean isEnabled(JsonGenerator.Feature f) {
867 return ObjectMapper.this.isEnabled(f);
868 }
869
870 // // // Mutant accessors
871
872 @Override
873 public MutableConfigOverride configOverride(Class<?> type) {
874 return ObjectMapper.this.configOverride(type);
875 }
876
877 // // // Methods for registering handlers: deserializers
878
879 @Override
880 public void addDeserializers(Deserializers d) {
881 DeserializerFactory df = _deserializationContext._factory.withAdditionalDeserializers(d);
882 _deserializationContext = _deserializationContext.with(df);
883 }
884
885 @Override
886 public void addKeyDeserializers(KeyDeserializers d) {
887 DeserializerFactory df = _deserializationContext._factory.withAdditionalKeyDeserializers(d);
888 _deserializationContext = _deserializationContext.with(df);
889 }
890
891 @Override
892 public void addBeanDeserializerModifier(BeanDeserializerModifier modifier) {
893 DeserializerFactory df = _deserializationContext._factory.withDeserializerModifier(modifier);
894 _deserializationContext = _deserializationContext.with(df);
895 }
896
897 // // // Methods for registering handlers: serializers
898
899 @Override
900 public void addSerializers(Serializers s) {
901 _serializerFactory = _serializerFactory.withAdditionalSerializers(s);
902 }
903
904 @Override
905 public void addKeySerializers(Serializers s) {
906 _serializerFactory = _serializerFactory.withAdditionalKeySerializers(s);
907 }
908
909 @Override
910 public void addBeanSerializerModifier(BeanSerializerModifier modifier) {
911 _serializerFactory = _serializerFactory.withSerializerModifier(modifier);
912 }
913
914 // // // Methods for registering handlers: other
915
916 @Override
917 public void addAbstractTypeResolver(AbstractTypeResolver resolver) {
918 DeserializerFactory df = _deserializationContext._factory.withAbstractTypeResolver(resolver);
919 _deserializationContext = _deserializationContext.with(df);
920 }
921
922 @Override
923 public void addTypeModifier(TypeModifier modifier) {
924 TypeFactory f = _typeFactory;
925 f = f.withModifier(modifier);
926 setTypeFactory(f);
927 }
928
929 @Override
930 public void addValueInstantiators(ValueInstantiators instantiators) {
931 DeserializerFactory df = _deserializationContext._factory.withValueInstantiators(instantiators);
932 _deserializationContext = _deserializationContext.with(df);
933 }
934
935 @Override
936 public void setClassIntrospector(ClassIntrospector ci) {
937 _deserializationConfig = _deserializationConfig.with(ci);
938 _serializationConfig = _serializationConfig.with(ci);
939 }
940
941 @Override
942 public void insertAnnotationIntrospector(AnnotationIntrospector ai) {
943 _deserializationConfig = _deserializationConfig.withInsertedAnnotationIntrospector(ai);
944 _serializationConfig = _serializationConfig.withInsertedAnnotationIntrospector(ai);
945 }
946
947 @Override
948 public void appendAnnotationIntrospector(AnnotationIntrospector ai) {
949 _deserializationConfig = _deserializationConfig.withAppendedAnnotationIntrospector(ai);
950 _serializationConfig = _serializationConfig.withAppendedAnnotationIntrospector(ai);
951 }
952
953 @Override
954 public void registerSubtypes(Class<?>... subtypes) {
955 ObjectMapper.this.registerSubtypes(subtypes);
956 }
957
958 @Override
959 public void registerSubtypes(NamedType... subtypes) {
960 ObjectMapper.this.registerSubtypes(subtypes);
961 }
962
963 @Override
964 public void registerSubtypes(Collection<Class<?>> subtypes) {
965 ObjectMapper.this.registerSubtypes(subtypes);
966 }
967
968 @Override
969 public void setMixInAnnotations(Class<?> target, Class<?> mixinSource) {
970 addMixIn(target, mixinSource);
971 }
972
973 @Override
974 public void addDeserializationProblemHandler(DeserializationProblemHandler handler) {
975 addHandler(handler);
976 }
977
978 @Override
979 public void setNamingStrategy(PropertyNamingStrategy naming) {
980 setPropertyNamingStrategy(naming);
981 }
982 });
983
984 return this;
985 }
986
987 /**
988 * Convenience method for registering specified modules in order;
989 * functionally equivalent to:
990 *<pre>
991 * for (Module module : modules) {
992 * registerModule(module);
993 * }
994 *</pre>
995 *
996 * @since 2.2
997 */
998 public ObjectMapper registerModules(Module... modules)
999 {
1000 for (Module module : modules) {
1001 registerModule(module);
1002 }
1003 return this;
1004 }
1005
1006 /**
1007 * Convenience method for registering specified modules in order;
1008 * functionally equivalent to:
1009 *<pre>
1010 * for (Module module : modules) {
1011 * registerModule(module);
1012 * }
1013 *</pre>
1014 *
1015 * @since 2.2
1016 */
1017 public ObjectMapper registerModules(Iterable<? extends Module> modules)
1018 {
1019 _assertNotNull("modules", modules);
1020 for (Module module : modules) {
1021 registerModule(module);
1022 }
1023 return this;
1024 }
1025
1026 /**
1027 * The set of {@link Module} typeIds that are registered in this
1028 * ObjectMapper. By default the typeId for a module is it's full
1029 * class name (see {@link Module#getTypeId()}).
1030 *
1031 * @since 2.9.6
1032 */
1033 public Set<Object> getRegisteredModuleIds()
1034 {
1035 return (_registeredModuleTypes == null) ?
1036 Collections.emptySet() : Collections.unmodifiableSet(_registeredModuleTypes);
1037 }
1038
1039 /**
1040 * Method for locating available methods, using JDK {@link ServiceLoader}
1041 * facility, along with module-provided SPI.
1042 *<p>
1043 * Note that method does not do any caching, so calls should be considered
1044 * potentially expensive.
1045 *
1046 * @since 2.2
1047 */
1048 public static List<Module> findModules() {
1049 return findModules(null);
1050 }
1051
1052 /**
1053 * Method for locating available methods, using JDK {@link ServiceLoader}
1054 * facility, along with module-provided SPI.
1055 *<p>
1056 * Note that method does not do any caching, so calls should be considered
1057 * potentially expensive.
1058 *
1059 * @since 2.2
1060 */
1061 public static List<Module> findModules(ClassLoader classLoader)
1062 {
1063 ArrayList<Module> modules = new ArrayList<Module>();
1064 ServiceLoader<Module> loader = secureGetServiceLoader(Module.class, classLoader);
1065 for (Module module : loader) {
1066 modules.add(module);
1067 }
1068 return modules;
1069 }
1070
1071 private static <T> ServiceLoader<T> secureGetServiceLoader(final Class<T> clazz, final ClassLoader classLoader) {
1072 final SecurityManager sm = System.getSecurityManager();
1073 if (sm == null) {
1074 return (classLoader == null) ?
1075 ServiceLoader.load(clazz) : ServiceLoader.load(clazz, classLoader);
1076 }
1077 return AccessController.doPrivileged(new PrivilegedAction<ServiceLoader<T>>() {
1078 @Override
1079 public ServiceLoader<T> run() {
1080 return (classLoader == null) ?
1081 ServiceLoader.load(clazz) : ServiceLoader.load(clazz, classLoader);
1082 }
1083 });
1084 }
1085
1086 /**
1087 * Convenience method that is functionally equivalent to:
1088 *<code>
1089 * mapper.registerModules(mapper.findModules());
1090 *</code>
1091 *<p>
1092 * As with {@link #findModules()}, no caching is done for modules, so care
1093 * needs to be taken to either create and share a single mapper instance;
1094 * or to cache introspected set of modules.
1095 *
1096 * @since 2.2
1097 */
1098 public ObjectMapper findAndRegisterModules() {
1099 return registerModules(findModules());
1100 }
1101
1102 /*
1103 /**********************************************************
1104 /* Factory methods for creating JsonGenerators (added in 2.11)
1105 /**********************************************************
1106 */
1107
1108 /**
1109 * Factory method for constructing properly initialized {@link JsonGenerator}
1110 * to write content using specified {@link OutputStream}.
1111 * Generator is not managed (or "owned") by mapper: caller is responsible
1112 * for properly closing it once content generation is complete.
1113 *
1114 * @since 2.11
1115 */
1116 public JsonGenerator createGenerator(OutputStream out) throws IOException {
1117 _assertNotNull("out", out);
1118 JsonGenerator g = _jsonFactory.createGenerator(out, JsonEncoding.UTF8);
1119 _serializationConfig.initialize(g);
1120 return g;
1121 }
1122
1123 /**
1124 * Factory method for constructing properly initialized {@link JsonGenerator}
1125 * to write content using specified {@link OutputStream} and encoding.
1126 * Generator is not managed (or "owned") by mapper: caller is responsible
1127 * for properly closing it once content generation is complete.
1128 *
1129 * @since 2.11
1130 */
1131 public JsonGenerator createGenerator(OutputStream out, JsonEncoding enc) throws IOException {
1132 _assertNotNull("out", out);
1133 JsonGenerator g = _jsonFactory.createGenerator(out, enc);
1134 _serializationConfig.initialize(g);
1135 return g;
1136 }
1137
1138 /**
1139 * Factory method for constructing properly initialized {@link JsonGenerator}
1140 * to write content using specified {@link Writer}.
1141 * Generator is not managed (or "owned") by mapper: caller is responsible
1142 * for properly closing it once content generation is complete.
1143 *
1144 * @since 2.11
1145 */
1146 public JsonGenerator createGenerator(Writer w) throws IOException {
1147 _assertNotNull("w", w);
1148 JsonGenerator g = _jsonFactory.createGenerator(w);
1149 _serializationConfig.initialize(g);
1150 return g;
1151 }
1152
1153 /**
1154 * Factory method for constructing properly initialized {@link JsonGenerator}
1155 * to write content to specified {@link File}, using specified encoding.
1156 * Generator is not managed (or "owned") by mapper: caller is responsible
1157 * for properly closing it once content generation is complete.
1158 *
1159 * @since 2.11
1160 */
1161 public JsonGenerator createGenerator(File outputFile, JsonEncoding enc) throws IOException {
1162 _assertNotNull("outputFile", outputFile);
1163 JsonGenerator g = _jsonFactory.createGenerator(outputFile, enc);
1164 _serializationConfig.initialize(g);
1165 return g;
1166 }
1167
1168 /**
1169 * Factory method for constructing properly initialized {@link JsonGenerator}
1170 * to write content using specified {@link DataOutput}.
1171 * Generator is not managed (or "owned") by mapper: caller is responsible
1172 * for properly closing it once content generation is complete.
1173 *
1174 * @since 2.11
1175 */
1176 public JsonGenerator createGenerator(DataOutput out) throws IOException {
1177 _assertNotNull("out", out);
1178 JsonGenerator g = _jsonFactory.createGenerator(out);
1179 _serializationConfig.initialize(g);
1180 return g;
1181 }
1182
1183 /*
1184 /**********************************************************
1185 /* Factory methods for creating JsonParsers (added in 2.11)
1186 /**********************************************************
1187 */
1188
1189 /**
1190 * Factory method for constructing properly initialized {@link JsonParser}
1191 * to read content from specified {@link File}.
1192 * Parser is not managed (or "owned") by ObjectMapper: caller is responsible
1193 * for properly closing it once content reading is complete.
1194 *
1195 * @since 2.11
1196 */
1197 public JsonParser createParser(File src) throws IOException {
1198 _assertNotNull("src", src);
1199 JsonParser p = _jsonFactory.createParser(src);
1200 _deserializationConfig.initialize(p);
1201 return p;
1202 }
1203
1204 /**
1205 * Factory method for constructing properly initialized {@link JsonParser}
1206 * to read content from specified {@link File}.
1207 * Parser is not managed (or "owned") by ObjectMapper: caller is responsible
1208 * for properly closing it once content reading is complete.
1209 *
1210 * @since 2.11
1211 */
1212 public JsonParser createParser(URL src) throws IOException {
1213 _assertNotNull("src", src);
1214 JsonParser p = _jsonFactory.createParser(src);
1215 _deserializationConfig.initialize(p);
1216 return p;
1217 }
1218
1219 /**
1220 * Factory method for constructing properly initialized {@link JsonParser}
1221 * to read content using specified {@link InputStream}.
1222 * Parser is not managed (or "owned") by ObjectMapper: caller is responsible
1223 * for properly closing it once content reading is complete.
1224 *
1225 * @since 2.11
1226 */
1227 public JsonParser createParser(InputStream in) throws IOException {
1228 _assertNotNull("in", in);
1229 JsonParser p = _jsonFactory.createParser(in);
1230 _deserializationConfig.initialize(p);
1231 return p;
1232 }
1233
1234 /**
1235 * Factory method for constructing properly initialized {@link JsonParser}
1236 * to read content using specified {@link Reader}.
1237 * Parser is not managed (or "owned") by ObjectMapper: caller is responsible
1238 * for properly closing it once content reading is complete.
1239 *
1240 * @since 2.11
1241 */
1242 public JsonParser createParser(Reader r) throws IOException {
1243 _assertNotNull("r", r);
1244 JsonParser p = _jsonFactory.createParser(r);
1245 _deserializationConfig.initialize(p);
1246 return p;
1247 }
1248
1249 /**
1250 * Factory method for constructing properly initialized {@link JsonParser}
1251 * to read content from specified byte array.
1252 * Parser is not managed (or "owned") by ObjectMapper: caller is responsible
1253 * for properly closing it once content reading is complete.
1254 *
1255 * @since 2.11
1256 */
1257 public JsonParser createParser(byte[] content) throws IOException {
1258 _assertNotNull("content", content);
1259 JsonParser p = _jsonFactory.createParser(content);
1260 _deserializationConfig.initialize(p);
1261 return p;
1262 }
1263
1264 /**
1265 * Factory method for constructing properly initialized {@link JsonParser}
1266 * to read content from specified byte array.
1267 * Parser is not managed (or "owned") by ObjectMapper: caller is responsible
1268 * for properly closing it once content reading is complete.
1269 *
1270 * @since 2.11
1271 */
1272 public JsonParser createParser(byte[] content, int offset, int len) throws IOException {
1273 _assertNotNull("content", content);
1274 JsonParser p = _jsonFactory.createParser(content, offset, len);
1275 _deserializationConfig.initialize(p);
1276 return p;
1277 }
1278
1279 /**
1280 * Factory method for constructing properly initialized {@link JsonParser}
1281 * to read content from specified String.
1282 * Parser is not managed (or "owned") by ObjectMapper: caller is responsible
1283 * for properly closing it once content reading is complete.
1284 *
1285 * @since 2.11
1286 */
1287 public JsonParser createParser(String content) throws IOException {
1288 _assertNotNull("content", content);
1289 JsonParser p = _jsonFactory.createParser(content);
1290 _deserializationConfig.initialize(p);
1291 return p;
1292 }
1293
1294 /**
1295 * Factory method for constructing properly initialized {@link JsonParser}
1296 * to read content from specified character array
1297 * Parser is not managed (or "owned") by ObjectMapper: caller is responsible
1298 * for properly closing it once content reading is complete.
1299 *
1300 * @since 2.11
1301 */
1302 public JsonParser createParser(char[] content) throws IOException {
1303 _assertNotNull("content", content);
1304 JsonParser p = _jsonFactory.createParser(content);
1305 _deserializationConfig.initialize(p);
1306 return p;
1307 }
1308
1309 /**
1310 * Factory method for constructing properly initialized {@link JsonParser}
1311 * to read content from specified character array.
1312 * Parser is not managed (or "owned") by ObjectMapper: caller is responsible
1313 * for properly closing it once content reading is complete.
1314 *
1315 * @since 2.11
1316 */
1317 public JsonParser createParser(char[] content, int offset, int len) throws IOException {
1318 _assertNotNull("content", content);
1319 JsonParser p = _jsonFactory.createParser(content, offset, len);
1320 _deserializationConfig.initialize(p);
1321 return p;
1322 }
1323
1324 /**
1325 * Factory method for constructing properly initialized {@link JsonParser}
1326 * to read content using specified {@link DataInput}.
1327 * Parser is not managed (or "owned") by ObjectMapper: caller is responsible
1328 * for properly closing it once content reading is complete.
1329 *
1330 * @since 2.11
1331 */
1332 public JsonParser createParser(DataInput content) throws IOException {
1333 _assertNotNull("content", content);
1334 JsonParser p = _jsonFactory.createParser(content);
1335 _deserializationConfig.initialize(p);
1336 return p;
1337 }
1338
1339 /**
1340 * Factory method for constructing properly initialized {@link JsonParser}
1341 * to read content using non-blocking (asynchronous) mode.
1342 * Parser is not managed (or "owned") by ObjectMapper: caller is responsible
1343 * for properly closing it once content reading is complete.
1344 *
1345 * @since 2.11
1346 */
1347 public JsonParser createNonBlockingByteArrayParser() throws IOException {
1348 JsonParser p = _jsonFactory.createNonBlockingByteArrayParser();
1349 _deserializationConfig.initialize(p);
1350 return p;
1351 }
1352
1353 /*
1354 /**********************************************************
1355 /* Configuration: main config object access
1356 /**********************************************************
1357 */
1358
1359 /**
1360 * Method that returns the shared default {@link SerializationConfig}
1361 * object that defines configuration settings for serialization.
1362 *<p>
1363 * Note that since instances are immutable, you can NOT change settings
1364 * by accessing an instance and calling methods: this will simply create
1365 * new instance of config object.
1366 */
1367 public SerializationConfig getSerializationConfig() {
1368 return _serializationConfig;
1369 }
1370
1371 /**
1372 * Method that returns
1373 * the shared default {@link DeserializationConfig} object
1374 * that defines configuration settings for deserialization.
1375 *<p>
1376 * Note that since instances are immutable, you can NOT change settings
1377 * by accessing an instance and calling methods: this will simply create
1378 * new instance of config object.
1379 */
1380 public DeserializationConfig getDeserializationConfig() {
1381 return _deserializationConfig;
1382 }
1383
1384 /**
1385 * Method for getting current {@link DeserializationContext}.
1386 *<p>
1387 * Note that since instances are immutable, you can NOT change settings
1388 * by accessing an instance and calling methods: this will simply create
1389 * new instance of context object.
1390 */
1391 public DeserializationContext getDeserializationContext() {
1392 return _deserializationContext;
1393 }
1394
1395 /*
1396 /**********************************************************
1397 /* Configuration: ser/deser factory, provider access
1398 /**********************************************************
1399 */
1400
1401 /**
1402 * Method for setting specific {@link SerializerFactory} to use
1403 * for constructing (bean) serializers.
1404 */
1405 public ObjectMapper setSerializerFactory(SerializerFactory f) {
1406 _serializerFactory = f;
1407 return this;
1408 }
1409
1410 /**
1411 * Method for getting current {@link SerializerFactory}.
1412 *<p>
1413 * Note that since instances are immutable, you can NOT change settings
1414 * by accessing an instance and calling methods: this will simply create
1415 * new instance of factory object.
1416 */
1417 public SerializerFactory getSerializerFactory() {
1418 return _serializerFactory;
1419 }
1420
1421 /**
1422 * Method for setting "blueprint" {@link SerializerProvider} instance
1423 * to use as the base for actual provider instances to use for handling
1424 * caching of {@link JsonSerializer} instances.
1425 */
1426 public ObjectMapper setSerializerProvider(DefaultSerializerProvider p) {
1427 _serializerProvider = p;
1428 return this;
1429 }
1430
1431 /**
1432 * Accessor for the "blueprint" (or, factory) instance, from which instances
1433 * are created by calling {@link DefaultSerializerProvider#createInstance}.
1434 * Note that returned instance cannot be directly used as it is not properly
1435 * configured: to get a properly configured instance to call, use
1436 * {@link #getSerializerProviderInstance()} instead.
1437 */
1438 public SerializerProvider getSerializerProvider() {
1439 return _serializerProvider;
1440 }
1441
1442 /**
1443 * Accessor for constructing and returning a {@link SerializerProvider}
1444 * instance that may be used for accessing serializers. This is same as
1445 * calling {@link #getSerializerProvider}, and calling <code>createInstance</code>
1446 * on it.
1447 *
1448 * @since 2.7
1449 */
1450 public SerializerProvider getSerializerProviderInstance() {
1451 return _serializerProvider(_serializationConfig);
1452 }
1453
1454 /*
1455 /**********************************************************
1456 /* Configuration: mix-in annotations
1457 /**********************************************************
1458 */
1459
1460 /**
1461 * Method to use for defining mix-in annotations to use for augmenting
1462 * annotations that processable (serializable / deserializable)
1463 * classes have.
1464 * Mixing in is done when introspecting class annotations and properties.
1465 * Map passed contains keys that are target classes (ones to augment
1466 * with new annotation overrides), and values that are source classes
1467 * (have annotations to use for augmentation).
1468 * Annotations from source classes (and their supertypes)
1469 * will <b>override</b>
1470 * annotations that target classes (and their super-types) have.
1471 *<p>
1472 * Note that this method will CLEAR any previously defined mix-ins
1473 * for this mapper.
1474 *
1475 * @since 2.5
1476 */
1477 public ObjectMapper setMixIns(Map<Class<?>, Class<?>> sourceMixins)
1478 {
1479 // NOTE: does NOT change possible externally configured resolver, just local defs
1480 _mixIns.setLocalDefinitions(sourceMixins);
1481 return this;
1482 }
1483
1484 /**
1485 * Method to use for adding mix-in annotations to use for augmenting
1486 * specified class or interface. All annotations from
1487 * <code>mixinSource</code> are taken to override annotations
1488 * that <code>target</code> (or its supertypes) has.
1489 *
1490 * @param target Class (or interface) whose annotations to effectively override
1491 * @param mixinSource Class (or interface) whose annotations are to
1492 * be "added" to target's annotations, overriding as necessary
1493 *
1494 * @since 2.5
1495 */
1496 public ObjectMapper addMixIn(Class<?> target, Class<?> mixinSource)
1497 {
1498 _mixIns.addLocalDefinition(target, mixinSource);
1499 return this;
1500 }
1501
1502 /**
1503 * Method that can be called to specify given resolver for locating
1504 * mix-in classes to use, overriding directly added mappings.
1505 * Note that direct mappings are not cleared, but they are only applied
1506 * if resolver does not provide mix-in matches.
1507 *
1508 * @since 2.6
1509 */
1510 public ObjectMapper setMixInResolver(ClassIntrospector.MixInResolver resolver)
1511 {
1512 SimpleMixInResolver r = _mixIns.withOverrides(resolver);
1513 if (r != _mixIns) {
1514 _mixIns = r;
1515 _deserializationConfig = new DeserializationConfig(_deserializationConfig, r);
1516 _serializationConfig = new SerializationConfig(_serializationConfig, r);
1517 }
1518 return this;
1519 }
1520
1521 public Class<?> findMixInClassFor(Class<?> cls) {
1522 return _mixIns.findMixInClassFor(cls);
1523 }
1524
1525 // For testing only:
1526 public int mixInCount() {
1527 return _mixIns.localSize();
1528 }
1529
1530 /**
1531 * @deprecated Since 2.5: replaced by a fluent form of the method; {@link #setMixIns}.
1532 */
1533 @Deprecated
1534 public void setMixInAnnotations(Map<Class<?>, Class<?>> sourceMixins) {
1535 setMixIns(sourceMixins);
1536 }
1537
1538 /**
1539 * @deprecated Since 2.5: replaced by a fluent form of the method; {@link #addMixIn(Class, Class)}.
1540 */
1541 @Deprecated
1542 public final void addMixInAnnotations(Class<?> target, Class<?> mixinSource) {
1543 addMixIn(target, mixinSource);
1544 }
1545
1546 /*
1547 /**********************************************************
1548 /* Configuration, introspection
1549 /**********************************************************
1550 */
1551
1552 /**
1553 * Method for accessing currently configured visibility checker;
1554 * object used for determining whether given property element
1555 * (method, field, constructor) can be auto-detected or not.
1556 */
1557 public VisibilityChecker<?> getVisibilityChecker() {
1558 return _serializationConfig.getDefaultVisibilityChecker();
1559 }
1560
1561 /**
1562 * Method for setting currently configured default {@link VisibilityChecker},
1563 * object used for determining whether given property element
1564 * (method, field, constructor) can be auto-detected or not.
1565 * This default checker is used as the base visibility:
1566 * per-class overrides (both via annotations and per-type config overrides)
1567 * can further change these settings.
1568 *
1569 * @since 2.6
1570 */
1571 public ObjectMapper setVisibility(VisibilityChecker<?> vc) {
1572 _configOverrides.setDefaultVisibility(vc);
1573 return this;
1574 }
1575
1576 /**
1577 * Convenience method that allows changing configuration for
1578 * underlying {@link VisibilityChecker}s, to change details of what kinds of
1579 * properties are auto-detected.
1580 * Basically short cut for doing:
1581 *<pre>
1582 * mapper.setVisibilityChecker(
1583 * mapper.getVisibilityChecker().withVisibility(forMethod, visibility)
1584 * );
1585 *</pre>
1586 * one common use case would be to do:
1587 *<pre>
1588 * mapper.setVisibility(JsonMethod.FIELD, Visibility.ANY);
1589 *</pre>
1590 * which would make all member fields serializable without further annotations,
1591 * instead of just public fields (default setting).
1592 *
1593 * @param forMethod Type of property descriptor affected (field, getter/isGetter,
1594 * setter, creator)
1595 * @param visibility Minimum visibility to require for the property descriptors of type
1596 *
1597 * @return Modified mapper instance (that is, "this"), to allow chaining
1598 * of configuration calls
1599 */
1600 public ObjectMapper setVisibility(PropertyAccessor forMethod, JsonAutoDetect.Visibility visibility)
1601 {
1602 VisibilityChecker<?> vc = _configOverrides.getDefaultVisibility();
1603 vc = vc.withVisibility(forMethod, visibility);
1604 _configOverrides.setDefaultVisibility(vc);
1605 return this;
1606 }
1607
1608 /**
1609 * Method for accessing subtype resolver in use.
1610 */
1611 public SubtypeResolver getSubtypeResolver() {
1612 return _subtypeResolver;
1613 }
1614
1615 /**
1616 * Method for setting custom subtype resolver to use.
1617 */
1618 public ObjectMapper setSubtypeResolver(SubtypeResolver str) {
1619 _subtypeResolver = str;
1620 _deserializationConfig = _deserializationConfig.with(str);
1621 _serializationConfig = _serializationConfig.with(str);
1622 return this;
1623 }
1624
1625 /**
1626 * Method for setting {@link AnnotationIntrospector} used by this
1627 * mapper instance for both serialization and deserialization.
1628 * Note that doing this will replace the current introspector, which
1629 * may lead to unavailability of core Jackson annotations.
1630 * If you want to combine handling of multiple introspectors,
1631 * have a look at {@link com.fasterxml.jackson.databind.introspect.AnnotationIntrospectorPair}.
1632 *
1633 * @see com.fasterxml.jackson.databind.introspect.AnnotationIntrospectorPair
1634 */
1635 public ObjectMapper setAnnotationIntrospector(AnnotationIntrospector ai) {
1636 _serializationConfig = _serializationConfig.with(ai);
1637 _deserializationConfig = _deserializationConfig.with(ai);
1638 return this;
1639 }
1640
1641 /**
1642 * Method for changing {@link AnnotationIntrospector} instances used
1643 * by this mapper instance for serialization and deserialization,
1644 * specifying them separately so that different introspection can be
1645 * used for different aspects
1646 *
1647 * @since 2.1
1648 *
1649 * @param serializerAI {@link AnnotationIntrospector} to use for configuring
1650 * serialization
1651 * @param deserializerAI {@link AnnotationIntrospector} to use for configuring
1652 * deserialization
1653 *
1654 * @see com.fasterxml.jackson.databind.introspect.AnnotationIntrospectorPair
1655 */
1656 public ObjectMapper setAnnotationIntrospectors(AnnotationIntrospector serializerAI,
1657 AnnotationIntrospector deserializerAI) {
1658 _serializationConfig = _serializationConfig.with(serializerAI);
1659 _deserializationConfig = _deserializationConfig.with(deserializerAI);
1660 return this;
1661 }
1662
1663 /**
1664 * Method for setting custom property naming strategy to use.
1665 */
1666 public ObjectMapper setPropertyNamingStrategy(PropertyNamingStrategy s) {
1667 _serializationConfig = _serializationConfig.with(s);
1668 _deserializationConfig = _deserializationConfig.with(s);
1669 return this;
1670 }
1671
1672 /**
1673 * @since 2.5
1674 */
1675 public PropertyNamingStrategy getPropertyNamingStrategy() {
1676 // arbitrary choice but let's do:
1677 return _serializationConfig.getPropertyNamingStrategy();
1678 }
1679
1680 /**
1681 * Method for specifying {@link PrettyPrinter} to use when "default pretty-printing"
1682 * is enabled (by enabling {@link SerializationFeature#INDENT_OUTPUT})
1683 *
1684 * @param pp Pretty printer to use by default.
1685 *
1686 * @return This mapper, useful for call-chaining
1687 *
1688 * @since 2.6
1689 */
1690 public ObjectMapper setDefaultPrettyPrinter(PrettyPrinter pp) {
1691 _serializationConfig = _serializationConfig.withDefaultPrettyPrinter(pp);
1692 return this;
1693 }
1694
1695 /**
1696 * @deprecated Since 2.6 use {@link #setVisibility(VisibilityChecker)} instead.
1697 */
1698 @Deprecated
1699 public void setVisibilityChecker(VisibilityChecker<?> vc) {
1700 setVisibility(vc);
1701 }
1702
1703 /**
1704 * Method for specifying {@link PolymorphicTypeValidator} to use for validating
1705 * polymorphic subtypes used with explicit polymorphic types (annotation-based),
1706 * but NOT one with "default typing" (see {@link #activateDefaultTyping(PolymorphicTypeValidator)}
1707 * for details).
1708 *
1709 * @since 2.10
1710 */
1711 public ObjectMapper setPolymorphicTypeValidator(PolymorphicTypeValidator ptv) {
1712 BaseSettings s = _deserializationConfig.getBaseSettings().with(ptv);
1713 _deserializationConfig = _deserializationConfig._withBase(s);
1714 return this;
1715 }
1716
1717 /**
1718 * Accessor for configured {@link PolymorphicTypeValidator} used for validating
1719 * polymorphic subtypes used with explicit polymorphic types (annotation-based),
1720 * but NOT one with "default typing" (see {@link #activateDefaultTyping(PolymorphicTypeValidator)}
1721 * for details).
1722 *
1723 * @since 2.10
1724 */
1725 public PolymorphicTypeValidator getPolymorphicTypeValidator() {
1726 return _deserializationConfig.getBaseSettings().getPolymorphicTypeValidator();
1727 }
1728
1729 /*
1730 /**********************************************************
1731 /* Configuration: global-default/per-type override settings
1732 /**********************************************************
1733 */
1734
1735 /**
1736 * Convenience method, equivalent to calling:
1737 *<pre>
1738 * setPropertyInclusion(JsonInclude.Value.construct(incl, incl));
1739 *</pre>
1740 *<p>
1741 * NOTE: behavior differs slightly from 2.8, where second argument was
1742 * implied to be <code>JsonInclude.Include.ALWAYS</code>.
1743 */
1744 public ObjectMapper setSerializationInclusion(JsonInclude.Include incl) {
1745 setPropertyInclusion(JsonInclude.Value.construct(incl, incl));
1746 return this;
1747 }
1748
1749 /**
1750 * @since 2.7
1751 * @deprecated Since 2.9 use {@link #setDefaultPropertyInclusion}
1752 */
1753 @Deprecated
1754 public ObjectMapper setPropertyInclusion(JsonInclude.Value incl) {
1755 return setDefaultPropertyInclusion(incl);
1756 }
1757
1758 /**
1759 * Method for setting default POJO property inclusion strategy for serialization,
1760 * applied for all properties for which there are no per-type or per-property
1761 * overrides (via annotations or config overrides).
1762 *
1763 * @since 2.9 (basically rename of <code>setPropertyInclusion</code>)
1764 */
1765 public ObjectMapper setDefaultPropertyInclusion(JsonInclude.Value incl) {
1766 _configOverrides.setDefaultInclusion(incl);
1767 return this;
1768 }
1769
1770 /**
1771 * Short-cut for:
1772 *<pre>
1773 * setDefaultPropertyInclusion(JsonInclude.Value.construct(incl, incl));
1774 *</pre>
1775 *
1776 * @since 2.9 (basically rename of <code>setPropertyInclusion</code>)
1777 */
1778 public ObjectMapper setDefaultPropertyInclusion(JsonInclude.Include incl) {
1779 _configOverrides.setDefaultInclusion(JsonInclude.Value.construct(incl, incl));
1780 return this;
1781 }
1782
1783 /**
1784 * Method for setting default Setter configuration, regarding things like
1785 * merging, null-handling; used for properties for which there are
1786 * no per-type or per-property overrides (via annotations or config overrides).
1787 *
1788 * @since 2.9
1789 */
1790 public ObjectMapper setDefaultSetterInfo(JsonSetter.Value v) {
1791 _configOverrides.setDefaultSetterInfo(v);
1792 return this;
1793 }
1794
1795 /**
1796 * Method for setting auto-detection visibility definition
1797 * defaults, which are in effect unless overridden by
1798 * annotations (like <code>JsonAutoDetect</code>) or per-type
1799 * visibility overrides.
1800 *
1801 * @since 2.9
1802 */
1803 public ObjectMapper setDefaultVisibility(JsonAutoDetect.Value vis) {
1804 _configOverrides.setDefaultVisibility(VisibilityChecker.Std.construct(vis));
1805 return this;
1806 }
1807
1808 /**
1809 * Method for setting default Setter configuration, regarding things like
1810 * merging, null-handling; used for properties for which there are
1811 * no per-type or per-property overrides (via annotations or config overrides).
1812 *
1813 * @since 2.9
1814 */
1815 public ObjectMapper setDefaultMergeable(Boolean b) {
1816 _configOverrides.setDefaultMergeable(b);
1817 return this;
1818 }
1819
1820 /**
1821 * @since 2.10
1822 */
1823 public ObjectMapper setDefaultLeniency(Boolean b) {
1824 _configOverrides.setDefaultLeniency(b);
1825 return this;
1826 }
1827
1828 /*
1829 /**********************************************************
1830 /* Subtype registration
1831 /**********************************************************
1832 */
1833
1834 /**
1835 * Method for registering specified class as a subtype, so that
1836 * typename-based resolution can link supertypes to subtypes
1837 * (as an alternative to using annotations).
1838 * Type for given class is determined from appropriate annotation;
1839 * or if missing, default name (unqualified class name)
1840 */
1841 public void registerSubtypes(Class<?>... classes) {
1842 getSubtypeResolver().registerSubtypes(classes);
1843 }
1844
1845 /**
1846 * Method for registering specified class as a subtype, so that
1847 * typename-based resolution can link supertypes to subtypes
1848 * (as an alternative to using annotations).
1849 * Name may be provided as part of argument, but if not will
1850 * be based on annotations or use default name (unqualified
1851 * class name).
1852 */
1853 public void registerSubtypes(NamedType... types) {
1854 getSubtypeResolver().registerSubtypes(types);
1855 }
1856
1857 /**
1858 * @since 2.9
1859 */
1860 public void registerSubtypes(Collection<Class<?>> subtypes) {
1861 getSubtypeResolver().registerSubtypes(subtypes);
1862 }
1863
1864 /*
1865 /**********************************************************
1866 /* Default typing (automatic polymorphic types): current (2.10)
1867 /**********************************************************
1868 */
1869
1870 /**
1871 * Convenience method that is equivalent to calling
1872 *<pre>
1873 * activateDefaultTyping(ptv, DefaultTyping.OBJECT_AND_NON_CONCRETE);
1874 *</pre>
1875 *<p>
1876 * NOTE: choice of {@link PolymorphicTypeValidator} to pass is critical for security
1877 * as allowing all subtypes can be risky for untrusted content.
1878 *
1879 * @param ptv Validator used to verify that actual subtypes to deserialize are valid against
1880 * whatever criteria validator uses: important in case where untrusted content is deserialized.
1881 *
1882 * @since 2.10
1883 */
1884 public ObjectMapper activateDefaultTyping(PolymorphicTypeValidator ptv) {
1885 return activateDefaultTyping(ptv, DefaultTyping.OBJECT_AND_NON_CONCRETE);
1886 }
1887
1888 /**
1889 * Convenience method that is equivalent to calling
1890 *<pre>
1891 * activateDefaultTyping(ptv, dti, JsonTypeInfo.As.WRAPPER_ARRAY);
1892 *</pre>
1893 *<p>
1894 * NOTE: choice of {@link PolymorphicTypeValidator} to pass is critical for security
1895 * as allowing all subtypes can be risky for untrusted content.
1896 *
1897 * @param ptv Validator used to verify that actual subtypes to deserialize are valid against
1898 * whatever criteria validator uses: important in case where untrusted content is deserialized.
1899 * @param applicability Defines kinds of types for which additional type information
1900 * is added; see {@link DefaultTyping} for more information.
1901 *
1902 * @since 2.10
1903 */
1904 public ObjectMapper activateDefaultTyping(PolymorphicTypeValidator ptv,
1905 DefaultTyping applicability) {
1906 return activateDefaultTyping(ptv, applicability, JsonTypeInfo.As.WRAPPER_ARRAY);
1907 }
1908
1909 /**
1910 * Method for enabling automatic inclusion of type information ("Default Typing"),
1911 * needed for proper deserialization of polymorphic types (unless types
1912 * have been annotated with {@link com.fasterxml.jackson.annotation.JsonTypeInfo}).
1913 *<P>
1914 * NOTE: use of {@code JsonTypeInfo.As#EXTERNAL_PROPERTY} <b>NOT SUPPORTED</b>;
1915 * and attempts of do so will throw an {@link IllegalArgumentException} to make
1916 * this limitation explicit.
1917 *<p>
1918 * NOTE: choice of {@link PolymorphicTypeValidator} to pass is critical for security
1919 * as allowing all subtypes can be risky for untrusted content.
1920 *
1921 * @param ptv Validator used to verify that actual subtypes to deserialize are valid against
1922 * whatever criteria validator uses: important in case where untrusted content is deserialized.
1923 * @param applicability Defines kinds of types for which additional type information
1924 * is added; see {@link DefaultTyping} for more information.
1925 * @param includeAs
1926 *
1927 * @since 2.10
1928 */
1929 public ObjectMapper activateDefaultTyping(PolymorphicTypeValidator ptv,
1930 DefaultTyping applicability, JsonTypeInfo.As includeAs)
1931 {
1932 // 18-Sep-2014, tatu: Let's add explicit check to ensure no one tries to
1933 // use "As.EXTERNAL_PROPERTY", since that will not work (with 2.5+)
1934 if (includeAs == JsonTypeInfo.As.EXTERNAL_PROPERTY) {
1935 throw new IllegalArgumentException("Cannot use includeAs of "+includeAs);
1936 }
1937
1938 TypeResolverBuilder<?> typer = _constructDefaultTypeResolverBuilder(applicability, ptv);
1939 // we'll always use full class name, when using defaulting
1940 typer = typer.init(JsonTypeInfo.Id.CLASS, null);
1941 typer = typer.inclusion(includeAs);
1942 return setDefaultTyping(typer);
1943 }
1944
1945 /**
1946 * Method for enabling automatic inclusion of type information ("Default Typing")
1947 * -- needed for proper deserialization of polymorphic types (unless types
1948 * have been annotated with {@link com.fasterxml.jackson.annotation.JsonTypeInfo}) --
1949 * using "As.PROPERTY" inclusion mechanism and specified property name
1950 * to use for inclusion (default being "@class" since default type information
1951 * always uses class name as type identifier)
1952 *<p>
1953 * NOTE: choice of {@link PolymorphicTypeValidator} to pass is critical for security
1954 * as allowing all subtypes can be risky for untrusted content.
1955 *
1956 * @param ptv Validator used to verify that actual subtypes to deserialize are valid against
1957 * whatever criteria validator uses: important in case where untrusted content is deserialized.
1958 * @param applicability Defines kinds of types for which additional type information
1959 * is added; see {@link DefaultTyping} for more information.
1960 * @param propertyName Name of property used for including type id for polymorphic values.
1961 *
1962 * @since 2.10
1963 */
1964 public ObjectMapper activateDefaultTypingAsProperty(PolymorphicTypeValidator ptv,
1965 DefaultTyping applicability, String propertyName)
1966 {
1967 TypeResolverBuilder<?> typer = _constructDefaultTypeResolverBuilder(applicability,
1968 ptv);
1969 // we'll always use full class name, when using defaulting
1970 typer = typer.init(JsonTypeInfo.Id.CLASS, null);
1971 typer = typer.inclusion(JsonTypeInfo.As.PROPERTY);
1972 typer = typer.typeProperty(propertyName);
1973 return setDefaultTyping(typer);
1974 }
1975
1976 /**
1977 * Method for disabling automatic inclusion of type information; if so, only
1978 * explicitly annotated types (ones with
1979 * {@link com.fasterxml.jackson.annotation.JsonTypeInfo}) will have
1980 * additional embedded type information.
1981 *
1982 * @since 2.10
1983 */
1984 public ObjectMapper deactivateDefaultTyping() {
1985 return setDefaultTyping(null);
1986 }
1987
1988 /**
1989 * Method for enabling automatic inclusion of type information ("Default Typing"),
1990 * using specified handler object for determining which types this affects,
1991 * as well as details of how information is embedded.
1992 *<p>
1993 * NOTE: use of Default Typing can be a potential security risk if incoming
1994 * content comes from untrusted sources, so care should be taken to use
1995 * a {@link TypeResolverBuilder} that can limit allowed classes to
1996 * deserialize. Note in particular that
1997 * {@link com.fasterxml.jackson.databind.jsontype.impl.StdTypeResolverBuilder}
1998 * DOES NOT limit applicability but creates type (de)serializers for all
1999 * types.
2000 *
2001 * @param typer Type information inclusion handler
2002 */
2003 public ObjectMapper setDefaultTyping(TypeResolverBuilder<?> typer) {
2004 _deserializationConfig = _deserializationConfig.with(typer);
2005 _serializationConfig = _serializationConfig.with(typer);
2006 return this;
2007 }
2008
2009 /*
2010 /**********************************************************
2011 /* Default typing (automatic polymorphic types): deprecated (pre-2.10)
2012 /**********************************************************
2013 */
2014
2015 /**
2016 * @deprecated Since 2.10 use {@link #activateDefaultTyping(PolymorphicTypeValidator)} instead
2017 */
2018 @Deprecated
2019 public ObjectMapper enableDefaultTyping() {
2020 return activateDefaultTyping(getPolymorphicTypeValidator());
2021 }
2022
2023 /**
2024 * @deprecated Since 2.10 use {@link #activateDefaultTyping(PolymorphicTypeValidator,DefaultTyping)} instead
2025 */
2026 @Deprecated
2027 public ObjectMapper enableDefaultTyping(DefaultTyping dti) {
2028 return enableDefaultTyping(dti, JsonTypeInfo.As.WRAPPER_ARRAY);
2029 }
2030
2031 /**
2032 * @deprecated Since 2.10 use {@link #activateDefaultTyping(PolymorphicTypeValidator,DefaultTyping,JsonTypeInfo.As)} instead
2033 */
2034 @Deprecated
2035 public ObjectMapper enableDefaultTyping(DefaultTyping applicability, JsonTypeInfo.As includeAs) {
2036 return activateDefaultTyping(getPolymorphicTypeValidator(), applicability, includeAs);
2037 }
2038
2039 /**
2040 * @deprecated Since 2.10 use {@link #activateDefaultTypingAsProperty(PolymorphicTypeValidator,DefaultTyping,String)} instead
2041 */
2042 @Deprecated
2043 public ObjectMapper enableDefaultTypingAsProperty(DefaultTyping applicability, String propertyName) {
2044 return activateDefaultTypingAsProperty(getPolymorphicTypeValidator(), applicability, propertyName);
2045 }
2046
2047 /**
2048 * @deprecated Since 2.10 use {@link #deactivateDefaultTyping} instead
2049 */
2050 @Deprecated
2051 public ObjectMapper disableDefaultTyping() {
2052 return setDefaultTyping(null);
2053 }
2054
2055 /*
2056 /**********************************************************
2057 /* Configuration, basic type handling
2058 /**********************************************************
2059 */
2060
2061 /**
2062 * Accessor for getting a mutable configuration override object for
2063 * given type, needed to add or change per-type overrides applied
2064 * to properties of given type.
2065 * Usage is through returned object by calling "setter" methods, which
2066 * directly modify override object and take effect directly.
2067 * For example you can do
2068 *<pre>
2069 * mapper.configOverride(java.util.Date.class)
2070 * .setFormat(JsonFormat.Value.forPattern("yyyy-MM-dd"));
2071 *</pre>
2072 * to change the default format to use for properties of type
2073 * {@link java.util.Date} (possibly further overridden by per-property
2074 * annotations)
2075 *
2076 * @since 2.8
2077 */
2078 public MutableConfigOverride configOverride(Class<?> type) {
2079 return _configOverrides.findOrCreateOverride(type);
2080 }
2081
2082 /*
2083 /**********************************************************
2084 /* Configuration, basic type handling
2085 /**********************************************************
2086 */
2087
2088 /**
2089 * Accessor for getting currently configured {@link TypeFactory} instance.
2090 */
2091 public TypeFactory getTypeFactory() {
2092 return _typeFactory;
2093 }
2094
2095 /**
2096 * Method that can be used to override {@link TypeFactory} instance
2097 * used by this mapper.
2098 *<p>
2099 * Note: will also set {@link TypeFactory} that deserialization and
2100 * serialization config objects use.
2101 */
2102 public ObjectMapper setTypeFactory(TypeFactory f)
2103 {
2104 _typeFactory = f;
2105 _deserializationConfig = _deserializationConfig.with(f);
2106 _serializationConfig = _serializationConfig.with(f);
2107 return this;
2108 }
2109
2110 /**
2111 * Convenience method for constructing {@link JavaType} out of given
2112 * type (typically <code>java.lang.Class</code>), but without explicit
2113 * context.
2114 */
2115 public JavaType constructType(Type t) {
2116 _assertNotNull("t", t);
2117 return _typeFactory.constructType(t);
2118 }
2119
2120 /*
2121 /**********************************************************
2122 /* Configuration, deserialization
2123 /**********************************************************
2124 */
2125
2126 /**
2127 * Method that can be used to get hold of {@link JsonNodeFactory}
2128 * that this mapper will use when directly constructing
2129 * root {@link JsonNode} instances for Trees.
2130 *<p>
2131 * Note: this is just a shortcut for calling
2132 *<pre>
2133 * getDeserializationConfig().getNodeFactory()
2134 *</pre>
2135 */
2136 public JsonNodeFactory getNodeFactory() {
2137 return _deserializationConfig.getNodeFactory();
2138 }
2139
2140 /**
2141 * Method for specifying {@link JsonNodeFactory} to use for
2142 * constructing root level tree nodes (via method
2143 * {@link #createObjectNode}
2144 */
2145 public ObjectMapper setNodeFactory(JsonNodeFactory f) {
2146 _deserializationConfig = _deserializationConfig.with(f);
2147 return this;
2148 }
2149
2150 /**
2151 * Method for adding specified {@link DeserializationProblemHandler}
2152 * to be used for handling specific problems during deserialization.
2153 */
2154 public ObjectMapper addHandler(DeserializationProblemHandler h) {
2155 _deserializationConfig = _deserializationConfig.withHandler(h);
2156 return this;
2157 }
2158
2159 /**
2160 * Method for removing all registered {@link DeserializationProblemHandler}s
2161 * instances from this mapper.
2162 */
2163 public ObjectMapper clearProblemHandlers() {
2164 _deserializationConfig = _deserializationConfig.withNoProblemHandlers();
2165 return this;
2166 }
2167
2168 /**
2169 * Method that allows overriding of the underlying {@link DeserializationConfig}
2170 * object.
2171 * It is added as a fallback method that may be used if no other configuration
2172 * modifier method works: it should not be used if there are alternatives,
2173 * and its use is generally discouraged.
2174 *<p>
2175 * <b>NOTE</b>: only use this method if you know what you are doing -- it allows
2176 * by-passing some of checks applied to other configuration methods.
2177 * Also keep in mind that as with all configuration of {@link ObjectMapper},
2178 * this is only thread-safe if done before calling any deserialization methods.
2179 *
2180 * @since 2.4
2181 */
2182 public ObjectMapper setConfig(DeserializationConfig config) {
2183 _assertNotNull("config", config);
2184 _deserializationConfig = config;
2185 return this;
2186 }
2187
2188 /*
2189 /**********************************************************
2190 /* Configuration, serialization
2191 /**********************************************************
2192 */
2193
2194 /**
2195 * @deprecated Since 2.6, use {@link #setFilterProvider} instead (allows chaining)
2196 */
2197 @Deprecated
2198 public void setFilters(FilterProvider filterProvider) {
2199 _serializationConfig = _serializationConfig.withFilters(filterProvider);
2200 }
2201
2202 /**
2203 * Method for configuring this mapper to use specified {@link FilterProvider} for
2204 * mapping Filter Ids to actual filter instances.
2205 *<p>
2206 * Note that usually it is better to use method {@link #writer(FilterProvider)};
2207 * however, sometimes
2208 * this method is more convenient. For example, some frameworks only allow configuring
2209 * of ObjectMapper instances and not {@link ObjectWriter}s.
2210 *
2211 * @since 2.6
2212 */
2213 public ObjectMapper setFilterProvider(FilterProvider filterProvider) {
2214 _serializationConfig = _serializationConfig.withFilters(filterProvider);
2215 return this;
2216 }
2217
2218 /**
2219 * Method that will configure default {@link Base64Variant} that
2220 * <code>byte[]</code> serializers and deserializers will use.
2221 *
2222 * @param v Base64 variant to use
2223 *
2224 * @return This mapper, for convenience to allow chaining
2225 *
2226 * @since 2.1
2227 */
2228 public ObjectMapper setBase64Variant(Base64Variant v) {
2229 _serializationConfig = _serializationConfig.with(v);
2230 _deserializationConfig = _deserializationConfig.with(v);
2231 return this;
2232 }
2233
2234 /**
2235 * Method that allows overriding of the underlying {@link SerializationConfig}
2236 * object, which contains serialization-specific configuration settings.
2237 * It is added as a fallback method that may be used if no other configuration
2238 * modifier method works: it should not be used if there are alternatives,
2239 * and its use is generally discouraged.
2240 *<p>
2241 * <b>NOTE</b>: only use this method if you know what you are doing -- it allows
2242 * by-passing some of checks applied to other configuration methods.
2243 * Also keep in mind that as with all configuration of {@link ObjectMapper},
2244 * this is only thread-safe if done before calling any serialization methods.
2245 *
2246 * @since 2.4
2247 */
2248 public ObjectMapper setConfig(SerializationConfig config) {
2249 _assertNotNull("config", config);
2250 _serializationConfig = config;
2251 return this;
2252 }
2253
2254 /*
2255 /**********************************************************
2256 /* Configuration, other
2257 /**********************************************************
2258 */
2259
2260 /**
2261 * Method that can be used to get hold of {@link JsonFactory} that this
2262 * mapper uses if it needs to construct {@link JsonParser}s
2263 * and/or {@link JsonGenerator}s.
2264 *<p>
2265 * WARNING: note that all {@link ObjectReader} and {@link ObjectWriter}
2266 * instances created by this mapper usually share the same configured
2267 * {@link JsonFactory}, so changes to its configuration will "leak".
2268 * To avoid such observed changes you should always use "with()" and
2269 * "without()" method of {@link ObjectReader} and {@link ObjectWriter}
2270 * for changing {@link com.fasterxml.jackson.core.JsonParser.Feature}
2271 * and {@link com.fasterxml.jackson.core.JsonGenerator.Feature}
2272 * settings to use on per-call basis.
2273 *
2274 * @return {@link JsonFactory} that this mapper uses when it needs to
2275 * construct Json parser and generators
2276 *
2277 * @since 2.10
2278 */
2279 public JsonFactory tokenStreamFactory() { return _jsonFactory; }
2280
2281 @Override
2282 public JsonFactory getFactory() { return _jsonFactory; }
2283
2284 /**
2285 * @deprecated Since 2.1: Use {@link #getFactory} instead
2286 */
2287 @Deprecated
2288 @Override
2289 public JsonFactory getJsonFactory() { return getFactory(); }
2290
2291 /**
2292 * Method for configuring the default {@link DateFormat} to use when serializing time
2293 * values as Strings, and deserializing from JSON Strings.
2294 * This is preferably to directly modifying {@link SerializationConfig} and
2295 * {@link DeserializationConfig} instances.
2296 * If you need per-request configuration, use {@link #writer(DateFormat)} to
2297 * create properly configured {@link ObjectWriter} and use that; this because
2298 * {@link ObjectWriter}s are thread-safe whereas ObjectMapper itself is only
2299 * thread-safe when configuring methods (such as this one) are NOT called.
2300 */
2301 public ObjectMapper setDateFormat(DateFormat dateFormat)
2302 {
2303 _deserializationConfig = _deserializationConfig.with(dateFormat);
2304 _serializationConfig = _serializationConfig.with(dateFormat);
2305 return this;
2306 }
2307
2308 /**
2309 * @since 2.5
2310 */
2311 public DateFormat getDateFormat() {
2312 // arbitrary choice but let's do:
2313 return _serializationConfig.getDateFormat();
2314 }
2315
2316 /**
2317 * Method for configuring {@link HandlerInstantiator} to use for creating
2318 * instances of handlers (such as serializers, deserializers, type and type
2319 * id resolvers), given a class.
2320 *
2321 * @param hi Instantiator to use; if null, use the default implementation
2322 */
2323 public Object setHandlerInstantiator(HandlerInstantiator hi)
2324 {
2325 _deserializationConfig = _deserializationConfig.with(hi);
2326 _serializationConfig = _serializationConfig.with(hi);
2327 return this;
2328 }
2329
2330 /**
2331 * Method for configuring {@link InjectableValues} which used to find
2332 * values to inject.
2333 */
2334 public ObjectMapper setInjectableValues(InjectableValues injectableValues) {
2335 _injectableValues = injectableValues;
2336 return this;
2337 }
2338
2339 /**
2340 * @since 2.6
2341 */
2342 public InjectableValues getInjectableValues() {
2343 return _injectableValues;
2344 }
2345
2346 /**
2347 * Method for overriding default locale to use for formatting.
2348 * Default value used is {@link Locale#getDefault()}.
2349 */
2350 public ObjectMapper setLocale(Locale l) {
2351 _deserializationConfig = _deserializationConfig.with(l);
2352 _serializationConfig = _serializationConfig.with(l);
2353 return this;
2354 }
2355
2356 /**
2357 * Method for overriding default TimeZone to use for formatting.
2358 * Default value used is UTC (NOT default TimeZone of JVM).
2359 */
2360 public ObjectMapper setTimeZone(TimeZone tz) {
2361 _deserializationConfig = _deserializationConfig.with(tz);
2362 _serializationConfig = _serializationConfig.with(tz);
2363 return this;
2364 }
2365
2366 /*
2367 /**********************************************************
2368 /* Configuration, simple features: MapperFeature
2369 /**********************************************************
2370 */
2371
2372 /**
2373 * Method for checking whether given {@link MapperFeature} is enabled.
2374 */
2375 public boolean isEnabled(MapperFeature f) {
2376 // ok to use either one, should be kept in sync
2377 return _serializationConfig.isEnabled(f);
2378 }
2379
2380 // Note: planned to be deprecated in 2.11 (not needed with 2.10):
2381 // @deprecated Since 2.10 use {@code JsonMapper.builder().configure(...)} (or similarly for other datatypes)
2382 // @Deprecated
2383 public ObjectMapper configure(MapperFeature f, boolean state) {
2384 _serializationConfig = state ?
2385 _serializationConfig.with(f) : _serializationConfig.without(f);
2386 _deserializationConfig = state ?
2387 _deserializationConfig.with(f) : _deserializationConfig.without(f);
2388 return this;
2389 }
2390
2391 // Note: planned to be deprecated in 2.11 (not needed with 2.10):
2392 // @deprecated Since 2.10 use {@code JsonMapper.builder().Enable(...)} (or similarly for other datatypes)
2393 // @Deprecated
2394 public ObjectMapper enable(MapperFeature... f) {
2395 _deserializationConfig = _deserializationConfig.with(f);
2396 _serializationConfig = _serializationConfig.with(f);
2397 return this;
2398 }
2399
2400 // Note: planned to be deprecated in 2.11 (not needed with 2.10):
2401 // @deprecated Since 2.10 use {@code JsonMapper.builder().disable(...)} (or similarly for other datatypes)
2402 // @Deprecated
2403 public ObjectMapper disable(MapperFeature... f) {
2404 _deserializationConfig = _deserializationConfig.without(f);
2405 _serializationConfig = _serializationConfig.without(f);
2406 return this;
2407 }
2408
2409 /*
2410 /**********************************************************
2411 /* Configuration, simple features: SerializationFeature
2412 /**********************************************************
2413 */
2414
2415 /**
2416 * Method for checking whether given serialization-specific
2417 * feature is enabled.
2418 */
2419 public boolean isEnabled(SerializationFeature f) {
2420 return _serializationConfig.isEnabled(f);
2421 }
2422
2423 /**
2424 * Method for changing state of an on/off serialization feature for
2425 * this object mapper.
2426 */
2427 public ObjectMapper configure(SerializationFeature f, boolean state) {
2428 _serializationConfig = state ?
2429 _serializationConfig.with(f) : _serializationConfig.without(f);
2430 return this;
2431 }
2432
2433 /**
2434 * Method for enabling specified {@link DeserializationConfig} feature.
2435 * Modifies and returns this instance; no new object is created.
2436 */
2437 public ObjectMapper enable(SerializationFeature f) {
2438 _serializationConfig = _serializationConfig.with(f);
2439 return this;
2440 }
2441
2442 /**
2443 * Method for enabling specified {@link DeserializationConfig} features.
2444 * Modifies and returns this instance; no new object is created.
2445 */
2446 public ObjectMapper enable(SerializationFeature first,
2447 SerializationFeature... f) {
2448 _serializationConfig = _serializationConfig.with(first, f);
2449 return this;
2450 }
2451
2452 /**
2453 * Method for enabling specified {@link DeserializationConfig} features.
2454 * Modifies and returns this instance; no new object is created.
2455 */
2456 public ObjectMapper disable(SerializationFeature f) {
2457 _serializationConfig = _serializationConfig.without(f);
2458 return this;
2459 }
2460
2461 /**
2462 * Method for enabling specified {@link DeserializationConfig} features.
2463 * Modifies and returns this instance; no new object is created.
2464 */
2465 public ObjectMapper disable(SerializationFeature first,
2466 SerializationFeature... f) {
2467 _serializationConfig = _serializationConfig.without(first, f);
2468 return this;
2469 }
2470
2471 /*
2472 /**********************************************************
2473 /* Configuration, simple features: DeserializationFeature
2474 /**********************************************************
2475 */
2476
2477 /**
2478 * Method for checking whether given deserialization-specific
2479 * feature is enabled.
2480 */
2481 public boolean isEnabled(DeserializationFeature f) {
2482 return _deserializationConfig.isEnabled(f);
2483 }
2484
2485 /**
2486 * Method for changing state of an on/off deserialization feature for
2487 * this object mapper.
2488 */
2489 public ObjectMapper configure(DeserializationFeature f, boolean state) {
2490 _deserializationConfig = state ?
2491 _deserializationConfig.with(f) : _deserializationConfig.without(f);
2492 return this;
2493 }
2494
2495 /**
2496 * Method for enabling specified {@link DeserializationConfig} features.
2497 * Modifies and returns this instance; no new object is created.
2498 */
2499 public ObjectMapper enable(DeserializationFeature feature) {
2500 _deserializationConfig = _deserializationConfig.with(feature);
2501 return this;
2502 }
2503
2504 /**
2505 * Method for enabling specified {@link DeserializationConfig} features.
2506 * Modifies and returns this instance; no new object is created.
2507 */
2508 public ObjectMapper enable(DeserializationFeature first,
2509 DeserializationFeature... f) {
2510 _deserializationConfig = _deserializationConfig.with(first, f);
2511 return this;
2512 }
2513
2514 /**
2515 * Method for enabling specified {@link DeserializationConfig} features.
2516 * Modifies and returns this instance; no new object is created.
2517 */
2518 public ObjectMapper disable(DeserializationFeature feature) {
2519 _deserializationConfig = _deserializationConfig.without(feature);
2520 return this;
2521 }
2522
2523 /**
2524 * Method for enabling specified {@link DeserializationConfig} features.
2525 * Modifies and returns this instance; no new object is created.
2526 */
2527 public ObjectMapper disable(DeserializationFeature first,
2528 DeserializationFeature... f) {
2529 _deserializationConfig = _deserializationConfig.without(first, f);
2530 return this;
2531 }
2532
2533 /*
2534 /**********************************************************
2535 /* Configuration, simple features: JsonParser.Feature
2536 /**********************************************************
2537 */
2538
2539 public boolean isEnabled(JsonParser.Feature f) {
2540 return _deserializationConfig.isEnabled(f, _jsonFactory);
2541 }
2542
2543 /**
2544 * Method for changing state of specified {@link com.fasterxml.jackson.core.JsonParser.Feature}s
2545 * for parser instances this object mapper creates.
2546 *<p>
2547 * Note that this is equivalent to directly calling same method
2548 * on {@link #getFactory}.
2549 *<p>
2550 * WARNING: since this method directly modifies state of underlying {@link JsonFactory},
2551 * it will change observed configuration by {@link ObjectReader}s as well -- to avoid
2552 * this, use {@link ObjectReader#with(JsonParser.Feature)} instead.
2553 */
2554 public ObjectMapper configure(JsonParser.Feature f, boolean state) {
2555 _jsonFactory.configure(f, state);
2556 return this;
2557 }
2558
2559 /**
2560 * Method for enabling specified {@link com.fasterxml.jackson.core.JsonParser.Feature}s
2561 * for parser instances this object mapper creates.
2562 *<p>
2563 * Note that this is equivalent to directly calling same method on {@link #getFactory}.
2564 *<p>
2565 * WARNING: since this method directly modifies state of underlying {@link JsonFactory},
2566 * it will change observed configuration by {@link ObjectReader}s as well -- to avoid
2567 * this, use {@link ObjectReader#with(JsonParser.Feature)} instead.
2568 *
2569 * @since 2.5
2570 */
2571 public ObjectMapper enable(JsonParser.Feature... features) {
2572 for (JsonParser.Feature f : features) {
2573 _jsonFactory.enable(f);
2574 }
2575 return this;
2576 }
2577
2578 /**
2579 * Method for disabling specified {@link com.fasterxml.jackson.core.JsonParser.Feature}s
2580 * for parser instances this object mapper creates.
2581 *<p>
2582 * Note that this is equivalent to directly calling same method on {@link #getFactory}.
2583 *<p>
2584 * WARNING: since this method directly modifies state of underlying {@link JsonFactory},
2585 * it will change observed configuration by {@link ObjectReader}s as well -- to avoid
2586 * this, use {@link ObjectReader#without(JsonParser.Feature)} instead.
2587 *
2588 * @since 2.5
2589 */
2590 public ObjectMapper disable(JsonParser.Feature... features) {
2591 for (JsonParser.Feature f : features) {
2592 _jsonFactory.disable(f);
2593 }
2594 return this;
2595 }
2596
2597 /*
2598 /**********************************************************
2599 /* Configuration, simple features: JsonGenerator.Feature
2600 /**********************************************************
2601 */
2602
2603 public boolean isEnabled(JsonGenerator.Feature f) {
2604 return _serializationConfig.isEnabled(f, _jsonFactory);
2605 }
2606
2607 /**
2608 * Method for changing state of an on/off {@link JsonGenerator} feature for
2609 * generator instances this object mapper creates.
2610 *<p>
2611 * Note that this is equivalent to directly calling same method
2612 * on {@link #getFactory}.
2613 *<p>
2614 * WARNING: since this method directly modifies state of underlying {@link JsonFactory},
2615 * it will change observed configuration by {@link ObjectWriter}s as well -- to avoid
2616 * this, use {@link ObjectWriter#with(JsonGenerator.Feature)} instead.
2617 */
2618 public ObjectMapper configure(JsonGenerator.Feature f, boolean state) {
2619 _jsonFactory.configure(f, state);
2620 return this;
2621 }
2622
2623 /**
2624 * Method for enabling specified {@link com.fasterxml.jackson.core.JsonGenerator.Feature}s
2625 * for parser instances this object mapper creates.
2626 *<p>
2627 * Note that this is equivalent to directly calling same method on {@link #getFactory}.
2628 *<p>
2629 * WARNING: since this method directly modifies state of underlying {@link JsonFactory},
2630 * it will change observed configuration by {@link ObjectWriter}s as well -- to avoid
2631 * this, use {@link ObjectWriter#with(JsonGenerator.Feature)} instead.
2632 *
2633 * @since 2.5
2634 */
2635 public ObjectMapper enable(JsonGenerator.Feature... features) {
2636 for (JsonGenerator.Feature f : features) {
2637 _jsonFactory.enable(f);
2638 }
2639 return this;
2640 }
2641
2642 /**
2643 * Method for disabling specified {@link com.fasterxml.jackson.core.JsonGenerator.Feature}s
2644 * for parser instances this object mapper creates.
2645 *<p>
2646 * Note that this is equivalent to directly calling same method on {@link #getFactory}.
2647 *<p>
2648 * WARNING: since this method directly modifies state of underlying {@link JsonFactory},
2649 * it will change observed configuration by {@link ObjectWriter}s as well -- to avoid
2650 * this, use {@link ObjectWriter#without(JsonGenerator.Feature)} instead.
2651 *
2652 * @since 2.5
2653 */
2654 public ObjectMapper disable(JsonGenerator.Feature... features) {
2655 for (JsonGenerator.Feature f : features) {
2656 _jsonFactory.disable(f);
2657 }
2658 return this;
2659 }
2660
2661 /*
2662 /**********************************************************
2663 /* Configuration, simple features: JsonFactory.Feature
2664 /**********************************************************
2665 */
2666
2667 /**
2668 * Convenience method, equivalent to:
2669 *<pre>
2670 * getJsonFactory().isEnabled(f);
2671 *</pre>
2672 */
2673 public boolean isEnabled(JsonFactory.Feature f) {
2674 return _jsonFactory.isEnabled(f);
2675 }
2676
2677 /*
2678 /**********************************************************
2679 /* Configuration, 2.10+ stream features
2680 /**********************************************************
2681 */
2682
2683 /**
2684 * @since 2.10
2685 */
2686 public boolean isEnabled(StreamReadFeature f) {
2687 return isEnabled(f.mappedFeature());
2688 }
2689
2690 /**
2691 * @since 2.10
2692 */
2693 public boolean isEnabled(StreamWriteFeature f) {
2694 return isEnabled(f.mappedFeature());
2695 }
2696
2697 /*
2698 /**********************************************************
2699 /* Public API (from ObjectCodec): deserialization
2700 /* (mapping from JSON to Java types);
2701 /* main methods
2702 /**********************************************************
2703 */
2704
2705 /**
2706 * Method to deserialize JSON content into a non-container
2707 * type (it can be an array type, however): typically a bean, array
2708 * or a wrapper type (like {@link java.lang.Boolean}).
2709 *<p>
2710 * Note: this method should NOT be used if the result type is a
2711 * container ({@link java.util.Collection} or {@link java.util.Map}.
2712 * The reason is that due to type erasure, key and value types
2713 * cannot be introspected when using this method.
2714 *
2715 * @throws IOException if a low-level I/O problem (unexpected end-of-input,
2716 * network error) occurs (passed through as-is without additional wrapping -- note
2717 * that this is one case where {@link DeserializationFeature#WRAP_EXCEPTIONS}
2718 * does NOT result in wrapping of exception even if enabled)
2719 * @throws JsonParseException if underlying input contains invalid content
2720 * of type {@link JsonParser} supports (JSON for default case)
2721 * @throws JsonMappingException if the input JSON structure does not match structure
2722 * expected for result type (or has other mismatch issues)
2723 */
2724 @Override
2725 @SuppressWarnings("unchecked")
2726 public <T> T readValue(JsonParser p, Class<T> valueType)
2727 throws IOException, JsonParseException, JsonMappingException
2728 {
2729 _assertNotNull("p", p);
2730 return (T) _readValue(getDeserializationConfig(), p, _typeFactory.constructType(valueType));
2731 }
2732
2733 /**
2734 * Method to deserialize JSON content into a Java type, reference
2735 * to which is passed as argument. Type is passed using so-called
2736 * "super type token" (see )
2737 * and specifically needs to be used if the root type is a
2738 * parameterized (generic) container type.
2739 *
2740 * @throws IOException if a low-level I/O problem (unexpected end-of-input,
2741 * network error) occurs (passed through as-is without additional wrapping -- note
2742 * that this is one case where {@link DeserializationFeature#WRAP_EXCEPTIONS}
2743 * does NOT result in wrapping of exception even if enabled)
2744 * @throws JsonParseException if underlying input contains invalid content
2745 * of type {@link JsonParser} supports (JSON for default case)
2746 * @throws JsonMappingException if the input JSON structure does not match structure
2747 * expected for result type (or has other mismatch issues)
2748 */
2749 @Override
2750 @SuppressWarnings("unchecked")
2751 public <T> T readValue(JsonParser p, TypeReference<T> valueTypeRef)
2752 throws IOException, JsonParseException, JsonMappingException
2753 {
2754 _assertNotNull("p", p);
2755 return (T) _readValue(getDeserializationConfig(), p, _typeFactory.constructType(valueTypeRef));
2756 }
2757
2758 /**
2759 * Method to deserialize JSON content into a Java type, reference
2760 * to which is passed as argument. Type is passed using
2761 * Jackson specific type; instance of which can be constructed using
2762 * {@link TypeFactory}.
2763 *
2764 * @throws IOException if a low-level I/O problem (unexpected end-of-input,
2765 * network error) occurs (passed through as-is without additional wrapping -- note
2766 * that this is one case where {@link DeserializationFeature#WRAP_EXCEPTIONS}
2767 * does NOT result in wrapping of exception even if enabled)
2768 * @throws JsonParseException if underlying input contains invalid content
2769 * of type {@link JsonParser} supports (JSON for default case)
2770 * @throws JsonMappingException if the input JSON structure does not match structure
2771 * expected for result type (or has other mismatch issues)
2772 */
2773 @Override
2774 @SuppressWarnings("unchecked")
2775 public final <T> T readValue(JsonParser p, ResolvedType valueType)
2776 throws IOException, JsonParseException, JsonMappingException
2777 {
2778 _assertNotNull("p", p);
2779 return (T) _readValue(getDeserializationConfig(), p, (JavaType) valueType);
2780 }
2781
2782 /**
2783 * Type-safe overloaded method, basically alias for {@link #readValue(JsonParser, Class)}.
2784 *
2785 * @throws IOException if a low-level I/O problem (unexpected end-of-input,
2786 * network error) occurs (passed through as-is without additional wrapping -- note
2787 * that this is one case where {@link DeserializationFeature#WRAP_EXCEPTIONS}
2788 * does NOT result in wrapping of exception even if enabled)
2789 * @throws JsonParseException if underlying input contains invalid content
2790 * of type {@link JsonParser} supports (JSON for default case)
2791 * @throws JsonMappingException if the input JSON structure does not match structure
2792 * expected for result type (or has other mismatch issues)
2793 */
2794 @SuppressWarnings("unchecked")
2795 public <T> T readValue(JsonParser p, JavaType valueType)
2796 throws IOException, JsonParseException, JsonMappingException
2797 {
2798 _assertNotNull("p", p);
2799 return (T) _readValue(getDeserializationConfig(), p, valueType);
2800 }
2801
2802 /**
2803 * Method to deserialize JSON content as a tree {@link JsonNode}.
2804 * Returns {@link JsonNode} that represents the root of the resulting tree, if there
2805 * was content to read, or {@code null} if no more content is accessible
2806 * via passed {@link JsonParser}.
2807 *<p>
2808 * NOTE! Behavior with end-of-input (no more content) differs between this
2809 * {@code readTree} method, and all other methods that take input source: latter
2810 * will return "missing node", NOT {@code null}
2811 *
2812 * @return a {@link JsonNode}, if valid JSON content found; null
2813 * if input has no content to bind -- note, however, that if
2814 * JSON <code>null</code> token is found, it will be represented
2815 * as a non-null {@link JsonNode} (one that returns <code>true</code>
2816 * for {@link JsonNode#isNull()}
2817 *
2818 * @throws IOException if a low-level I/O problem (unexpected end-of-input,
2819 * network error) occurs (passed through as-is without additional wrapping -- note
2820 * that this is one case where {@link DeserializationFeature#WRAP_EXCEPTIONS}
2821 * does NOT result in wrapping of exception even if enabled)
2822 * @throws JsonParseException if underlying input contains invalid content
2823 * of type {@link JsonParser} supports (JSON for default case)
2824 */
2825 @Override
2826 public <T extends TreeNode> T readTree(JsonParser p)
2827 throws IOException, JsonProcessingException
2828 {
2829 _assertNotNull("p", p);
2830 // Must check for EOF here before calling readValue(), since that'll choke on it otherwise
2831 DeserializationConfig cfg = getDeserializationConfig();
2832 JsonToken t = p.getCurrentToken();
2833 if (t == null) {
2834 t = p.nextToken();
2835 if (t == null) {
2836 return null;
2837 }
2838 }
2839 // NOTE! _readValue() will check for trailing tokens
2840 JsonNode n = (JsonNode) _readValue(cfg, p, constructType(JsonNode.class));
2841 if (n == null) {
2842 n = getNodeFactory().nullNode();
2843 }
2844 @SuppressWarnings("unchecked")
2845 T result = (T) n;
2846 return result;
2847 }
2848
2849 /**
2850 * Convenience method, equivalent in function to:
2851 *<pre>
2852 * readerFor(valueType).readValues(p);
2853 *</pre>
2854 *<p>
2855 * Method for reading sequence of Objects from parser stream.
2856 * Sequence can be either root-level "unwrapped" sequence (without surrounding
2857 * JSON array), or a sequence contained in a JSON Array.
2858 * In either case {@link JsonParser} <b>MUST</b> point to the first token of
2859 * the first element, OR not point to any token (in which case it is advanced
2860 * to the next token). This means, specifically, that for wrapped sequences,
2861 * parser MUST NOT point to the surrounding <code>START_ARRAY</code> (one that
2862 * contains values to read) but rather to the token following it which is the first
2863 * token of the first value to read.
2864 *<p>
2865 * Note that {@link ObjectReader} has more complete set of variants.
2866 */
2867 @Override
2868 public <T> MappingIterator<T> readValues(JsonParser p, ResolvedType valueType)
2869 throws IOException, JsonProcessingException
2870 {
2871 return readValues(p, (JavaType) valueType);
2872 }
2873
2874 /**
2875 * Convenience method, equivalent in function to:
2876 *<pre>
2877 * readerFor(valueType).readValues(p);
2878 *</pre>
2879 *<p>
2880 * Type-safe overload of {@link #readValues(JsonParser, ResolvedType)}.
2881 */
2882 public <T> MappingIterator<T> readValues(JsonParser p, JavaType valueType)
2883 throws IOException, JsonProcessingException
2884 {
2885 _assertNotNull("p", p);
2886 DeserializationConfig config = getDeserializationConfig();
2887 DeserializationContext ctxt = createDeserializationContext(p, config);
2888 JsonDeserializer<?> deser = _findRootDeserializer(ctxt, valueType);
2889 // false -> do NOT close JsonParser (since caller passed it)
2890 return new MappingIterator<T>(valueType, p, ctxt, deser,
2891 false, null);
2892 }
2893
2894 /**
2895 * Convenience method, equivalent in function to:
2896 *<pre>
2897 * readerFor(valueType).readValues(p);
2898 *</pre>
2899 *<p>
2900 * Type-safe overload of {@link #readValues(JsonParser, ResolvedType)}.
2901 */
2902 @Override
2903 public <T> MappingIterator<T> readValues(JsonParser p, Class<T> valueType)
2904 throws IOException, JsonProcessingException
2905 {
2906 return readValues(p, _typeFactory.constructType(valueType));
2907 }
2908
2909 /**
2910 * Method for reading sequence of Objects from parser stream.
2911 */
2912 @Override
2913 public <T> MappingIterator<T> readValues(JsonParser p, TypeReference<T> valueTypeRef)
2914 throws IOException, JsonProcessingException
2915 {
2916 return readValues(p, _typeFactory.constructType(valueTypeRef));
2917 }
2918
2919 /*
2920 /**********************************************************
2921 /* Public API not included in ObjectCodec: deserialization
2922 /* (mapping from JSON to Java types)
2923 /**********************************************************
2924 */
2925
2926 /**
2927 * Method to deserialize JSON content as tree expressed
2928 * using set of {@link JsonNode} instances.
2929 * Returns root of the resulting tree (where root can consist
2930 * of just a single node if the current event is a
2931 * value event, not container).
2932 *<p>
2933 * If a low-level I/O problem (missing input, network error) occurs,
2934 * a {@link IOException} will be thrown.
2935 * If a parsing problem occurs (invalid JSON),
2936 * {@link JsonParseException} will be thrown.
2937 * If no content is found from input (end-of-input), Java
2938 * <code>null</code> will be returned.
2939 *
2940 * @param in Input stream used to read JSON content
2941 * for building the JSON tree.
2942 *
2943 * @return a {@link JsonNode}, if valid JSON content found; null
2944 * if input has no content to bind -- note, however, that if
2945 * JSON <code>null</code> token is found, it will be represented
2946 * as a non-null {@link JsonNode} (one that returns <code>true</code>
2947 * for {@link JsonNode#isNull()}
2948 *
2949 * @throws JsonParseException if underlying input contains invalid content
2950 * of type {@link JsonParser} supports (JSON for default case)
2951 */
2952 public JsonNode readTree(InputStream in) throws IOException
2953 {
2954 _assertNotNull("in", in);
2955 return _readTreeAndClose(_jsonFactory.createParser(in));
2956 }
2957
2958 /**
2959 * Same as {@link #readTree(InputStream)} except content accessed through
2960 * passed-in {@link Reader}
2961 */
2962 public JsonNode readTree(Reader r) throws IOException {
2963 _assertNotNull("r", r);
2964 return _readTreeAndClose(_jsonFactory.createParser(r));
2965 }
2966
2967 /**
2968 * Same as {@link #readTree(InputStream)} except content read from
2969 * passed-in {@link String}
2970 */
2971 public JsonNode readTree(String content) throws JsonProcessingException, JsonMappingException {
2972 _assertNotNull("content", content);
2973 try { // since 2.10 remove "impossible" IOException as per [databind#1675]
2974 return _readTreeAndClose(_jsonFactory.createParser(content));
2975 } catch (JsonProcessingException e) {
2976 throw e;
2977 } catch (IOException e) { // shouldn't really happen but being declared need to
2978 throw JsonMappingException.fromUnexpectedIOE(e);
2979 }
2980 }
2981
2982 /**
2983 * Same as {@link #readTree(InputStream)} except content read from
2984 * passed-in byte array.
2985 */
2986 public JsonNode readTree(byte[] content) throws IOException {
2987 _assertNotNull("content", content);
2988 return _readTreeAndClose(_jsonFactory.createParser(content));
2989 }
2990
2991 /**
2992 * Same as {@link #readTree(InputStream)} except content read from
2993 * passed-in byte array.
2994 */
2995 public JsonNode readTree(byte[] content, int offset, int len) throws IOException {
2996 _assertNotNull("content", content);
2997 return _readTreeAndClose(_jsonFactory.createParser(content, offset, len));
2998 }
2999
3000 /**
3001 * Same as {@link #readTree(InputStream)} except content read from
3002 * passed-in {@link File}.
3003 */
3004 public JsonNode readTree(File file)
3005 throws IOException, JsonProcessingException
3006 {
3007 _assertNotNull("file", file);
3008 return _readTreeAndClose(_jsonFactory.createParser(file));
3009 }
3010
3011 /**
3012 * Same as {@link #readTree(InputStream)} except content read from
3013 * passed-in {@link URL}.
3014 *<p>
3015 * NOTE: handling of {@link java.net.URL} is delegated to
3016 * {@link JsonFactory#createParser(java.net.URL)} and usually simply
3017 * calls {@link java.net.URL#openStream()}, meaning no special handling
3018 * is done. If different HTTP connection options are needed you will need
3019 * to create {@link java.io.InputStream} separately.
3020 */
3021 public JsonNode readTree(URL source) throws IOException {
3022 _assertNotNull("source", source);
3023 return _readTreeAndClose(_jsonFactory.createParser(source));
3024 }
3025
3026 /*
3027 /**********************************************************
3028 /* Public API (from ObjectCodec): serialization
3029 /* (mapping from Java types to Json)
3030 /**********************************************************
3031 */
3032
3033 /**
3034 * Method that can be used to serialize any Java value as
3035 * JSON output, using provided {@link JsonGenerator}.
3036 */
3037 @Override
3038 public void writeValue(JsonGenerator g, Object value)
3039 throws IOException, JsonGenerationException, JsonMappingException
3040 {
3041 _assertNotNull("g", g);
3042 SerializationConfig config = getSerializationConfig();
3043
3044 /* 12-May-2015/2.6, tatu: Looks like we do NOT want to call the usual
3045 * 'config.initialize(g)` here, since it is assumed that generator
3046 * has been configured by caller. But for some reason we don't
3047 * trust indentation settings...
3048 */
3049 // 10-Aug-2012, tatu: as per [Issue#12], must handle indentation:
3050 if (config.isEnabled(SerializationFeature.INDENT_OUTPUT)) {
3051 if (g.getPrettyPrinter() == null) {
3052 g.setPrettyPrinter(config.constructDefaultPrettyPrinter());
3053 }
3054 }
3055 if (config.isEnabled(SerializationFeature.CLOSE_CLOSEABLE) && (value instanceof Closeable)) {
3056 _writeCloseableValue(g, value, config);
3057 } else {
3058 _serializerProvider(config).serializeValue(g, value);
3059 if (config.isEnabled(SerializationFeature.FLUSH_AFTER_WRITE_VALUE)) {
3060 g.flush();
3061 }
3062 }
3063 }
3064
3065 /*
3066 /**********************************************************
3067 /* Public API (from TreeCodec via ObjectCodec): Tree Model support
3068 /**********************************************************
3069 */
3070
3071 @Override
3072 public void writeTree(JsonGenerator g, TreeNode rootNode)
3073 throws IOException, JsonProcessingException
3074 {
3075 _assertNotNull("g", g);
3076 SerializationConfig config = getSerializationConfig();
3077 _serializerProvider(config).serializeValue(g, rootNode);
3078 if (config.isEnabled(SerializationFeature.FLUSH_AFTER_WRITE_VALUE)) {
3079 g.flush();
3080 }
3081 }
3082
3083 /**
3084 * Method to serialize given JSON Tree, using generator
3085 * provided.
3086 */
3087 public void writeTree(JsonGenerator g, JsonNode rootNode)
3088 throws IOException, JsonProcessingException
3089 {
3090 _assertNotNull("g", g);
3091 SerializationConfig config = getSerializationConfig();
3092 _serializerProvider(config).serializeValue(g, rootNode);
3093 if (config.isEnabled(SerializationFeature.FLUSH_AFTER_WRITE_VALUE)) {
3094 g.flush();
3095 }
3096 }
3097
3098 /**
3099 *<p>
3100 * Note: return type is co-variant, as basic ObjectCodec
3101 * abstraction cannot refer to concrete node types (as it's
3102 * part of core package, whereas impls are part of mapper
3103 * package)
3104 */
3105 @Override
3106 public ObjectNode createObjectNode() {
3107 return _deserializationConfig.getNodeFactory().objectNode();
3108 }
3109
3110 /**
3111 *<p>
3112 * Note: return type is co-variant, as basic ObjectCodec
3113 * abstraction cannot refer to concrete node types (as it's
3114 * part of core package, whereas impls are part of mapper
3115 * package)
3116 */
3117 @Override
3118 public ArrayNode createArrayNode() {
3119 return _deserializationConfig.getNodeFactory().arrayNode();
3120 }
3121
3122 @Override // since 2.10
3123 public JsonNode missingNode() {
3124 return _deserializationConfig.getNodeFactory().missingNode();
3125 }
3126
3127 @Override // since 2.10
3128 public JsonNode nullNode() {
3129 return _deserializationConfig.getNodeFactory().nullNode();
3130 }
3131
3132 /**
3133 * Method for constructing a {@link JsonParser} out of JSON tree
3134 * representation.
3135 *
3136 * @param n Root node of the tree that resulting parser will read from
3137 */
3138 @Override
3139 public JsonParser treeAsTokens(TreeNode n) {
3140 _assertNotNull("n", n);
3141 return new TreeTraversingParser((JsonNode) n, this);
3142 }
3143
3144 /**
3145 * Convenience conversion method that will bind data given JSON tree
3146 * contains into specific value (usually bean) type.
3147 *<p>
3148 * Functionally equivalent to:
3149 *<pre>
3150 * objectMapper.convertValue(n, valueClass);
3151 *</pre>
3152 */
3153 @SuppressWarnings("unchecked")
3154 @Override
3155 public <T> T treeToValue(TreeNode n, Class<T> valueType)
3156 throws JsonProcessingException
3157 {
3158 if (n == null) {
3159 return null;
3160 }
3161 try {
3162 // 25-Jan-2019, tatu: [databind#2220] won't prevent existing coercions here
3163 // Simple cast when we just want to cast to, say, ObjectNode
3164 if (TreeNode.class.isAssignableFrom(valueType)
3165 && valueType.isAssignableFrom(n.getClass())) {
3166 return (T) n;
3167 }
3168 final JsonToken tt = n.asToken();
3169 // 22-Aug-2019, tatu: [databind#2430] Consider "null node" (minor optimization)
3170 if (tt == JsonToken.VALUE_NULL) {
3171 return null;
3172 }
3173 // 20-Apr-2016, tatu: Another thing: for VALUE_EMBEDDED_OBJECT, assume similar
3174 // short-cut coercion
3175 if (tt == JsonToken.VALUE_EMBEDDED_OBJECT) {
3176 if (n instanceof POJONode) {
3177 Object ob = ((POJONode) n).getPojo();
3178 if ((ob == null) || valueType.isInstance(ob)) {
3179 return (T) ob;
3180 }
3181 }
3182 }
3183 return readValue(treeAsTokens(n), valueType);
3184 } catch (JsonProcessingException e) {
3185 throw e;
3186 } catch (IOException e) { // should not occur, no real i/o...
3187 throw new IllegalArgumentException(e.getMessage(), e);
3188 }
3189 }
3190
3191 /**
3192 * Reverse of {@link #treeToValue}; given a value (usually bean), will
3193 * construct equivalent JSON Tree representation. Functionally similar
3194 * to serializing value into JSON and parsing JSON as tree, but
3195 * more efficient.
3196 *<p>
3197 * NOTE: while results are usually identical to that of serialization followed
3198 * by deserialization, this is not always the case. In some cases serialization
3199 * into intermediate representation will retain encapsulation of things like
3200 * raw value ({@link com.fasterxml.jackson.databind.util.RawValue}) or basic
3201 * node identity ({@link JsonNode}). If so, result is a valid tree, but values
3202 * are not re-constructed through actual JSON representation. So if transformation
3203 * requires actual materialization of JSON (or other data format that this mapper
3204 * produces), it will be necessary to do actual serialization.
3205 *
3206 * @param <T> Actual node type; usually either basic {@link JsonNode} or
3207 * {@link com.fasterxml.jackson.databind.node.ObjectNode}
3208 * @param fromValue Bean value to convert
3209 *
3210 * @return (non-null) Root node of the resulting JSON tree: in case of {@code null} value,
3211 * node for which {@link JsonNode#isNull()} returns {@code true}.
3212 */
3213 @SuppressWarnings({ "unchecked", "resource" })
3214 public <T extends JsonNode> T valueToTree(Object fromValue)
3215 throws IllegalArgumentException
3216 {
3217 // [databind#2430]: `null` should become "null node":
3218 if (fromValue == null) {
3219 return (T) getNodeFactory().nullNode();
3220 }
3221 TokenBuffer buf = new TokenBuffer(this, false);
3222 if (isEnabled(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS)) {
3223 buf = buf.forceUseOfBigDecimal(true);
3224 }
3225 JsonNode result;
3226 try {
3227 writeValue(buf, fromValue);
3228 JsonParser p = buf.asParser();
3229 result = readTree(p);
3230 p.close();
3231 } catch (IOException e) { // should not occur, no real i/o...
3232 throw new IllegalArgumentException(e.getMessage(), e);
3233 }
3234 return (T) result;
3235 }
3236
3237 /*
3238 /**********************************************************
3239 /* Extended Public API, accessors
3240 /**********************************************************
3241 */
3242
3243 /**
3244 * Method that can be called to check whether mapper thinks
3245 * it could serialize an instance of given Class.
3246 * Check is done
3247 * by checking whether a serializer can be found for the type.
3248 *<p>
3249 * NOTE: since this method does NOT throw exceptions, but internal
3250 * processing may, caller usually has little information as to why
3251 * serialization would fail. If you want access to internal {@link Exception},
3252 * call {@link #canSerialize(Class, AtomicReference)} instead.
3253 *
3254 * @return True if mapper can find a serializer for instances of
3255 * given class (potentially serializable), false otherwise (not
3256 * serializable)
3257 */
3258 public boolean canSerialize(Class<?> type) {
3259 return _serializerProvider(getSerializationConfig()).hasSerializerFor(type, null);
3260 }
3261
3262 /**
3263 * Method similar to {@link #canSerialize(Class)} but that can return
3264 * actual {@link Throwable} that was thrown when trying to construct
3265 * serializer: this may be useful in figuring out what the actual problem is.
3266 *
3267 * @since 2.3
3268 */
3269 public boolean canSerialize(Class<?> type, AtomicReference<Throwable> cause) {
3270 return _serializerProvider(getSerializationConfig()).hasSerializerFor(type, cause);
3271 }
3272
3273 /**
3274 * Method that can be called to check whether mapper thinks
3275 * it could deserialize an Object of given type.
3276 * Check is done by checking whether a registered deserializer can
3277 * be found or built for the type; if not (either by no mapping being
3278 * found, or through an <code>Exception</code> being thrown, false
3279 * is returned.
3280 *<p>
3281 * <b>NOTE</b>: in case an exception is thrown during course of trying
3282 * co construct matching deserializer, it will be effectively swallowed.
3283 * If you want access to that exception, call
3284 * {@link #canDeserialize(JavaType, AtomicReference)} instead.
3285 *
3286 * @return True if mapper can find a serializer for instances of
3287 * given class (potentially serializable), false otherwise (not
3288 * serializable)
3289 */
3290 public boolean canDeserialize(JavaType type)
3291 {
3292 return createDeserializationContext(null,
3293 getDeserializationConfig()).hasValueDeserializerFor(type, null);
3294 }
3295
3296 /**
3297 * Method similar to {@link #canDeserialize(JavaType)} but that can return
3298 * actual {@link Throwable} that was thrown when trying to construct
3299 * serializer: this may be useful in figuring out what the actual problem is.
3300 *
3301 * @since 2.3
3302 */
3303 public boolean canDeserialize(JavaType type, AtomicReference<Throwable> cause)
3304 {
3305 return createDeserializationContext(null,
3306 getDeserializationConfig()).hasValueDeserializerFor(type, cause);
3307 }
3308
3309 /*
3310 /**********************************************************
3311 /* Extended Public API, deserialization,
3312 /* convenience methods
3313 /**********************************************************
3314 */
3315
3316 /**
3317 * Method to deserialize JSON content from given file into given Java type.
3318 *
3319 * @throws IOException if a low-level I/O problem (unexpected end-of-input,
3320 * network error) occurs (passed through as-is without additional wrapping -- note
3321 * that this is one case where {@link DeserializationFeature#WRAP_EXCEPTIONS}
3322 * does NOT result in wrapping of exception even if enabled)
3323 * @throws JsonParseException if underlying input contains invalid content
3324 * of type {@link JsonParser} supports (JSON for default case)
3325 * @throws JsonMappingException if the input JSON structure does not match structure
3326 * expected for result type (or has other mismatch issues)
3327 */
3328 @SuppressWarnings("unchecked")
3329 public <T> T readValue(File src, Class<T> valueType)
3330 throws IOException, JsonParseException, JsonMappingException
3331 {
3332 _assertNotNull("src", src);
3333 return (T) _readMapAndClose(_jsonFactory.createParser(src), _typeFactory.constructType(valueType));
3334 }
3335
3336 /**
3337 * Method to deserialize JSON content from given file into given Java type.
3338 *
3339 * @throws IOException if a low-level I/O problem (unexpected end-of-input,
3340 * network error) occurs (passed through as-is without additional wrapping -- note
3341 * that this is one case where {@link DeserializationFeature#WRAP_EXCEPTIONS}
3342 * does NOT result in wrapping of exception even if enabled)
3343 * @throws JsonParseException if underlying input contains invalid content
3344 * of type {@link JsonParser} supports (JSON for default case)
3345 * @throws JsonMappingException if the input JSON structure does not match structure
3346 * expected for result type (or has other mismatch issues)
3347 */
3348 @SuppressWarnings({ "unchecked" })
3349 public <T> T readValue(File src, TypeReference<T> valueTypeRef)
3350 throws IOException, JsonParseException, JsonMappingException
3351 {
3352 _assertNotNull("src", src);
3353 return (T) _readMapAndClose(_jsonFactory.createParser(src), _typeFactory.constructType(valueTypeRef));
3354 }
3355
3356 /**
3357 * Method to deserialize JSON content from given file into given Java type.
3358 *
3359 * @throws IOException if a low-level I/O problem (unexpected end-of-input,
3360 * network error) occurs (passed through as-is without additional wrapping -- note
3361 * that this is one case where {@link DeserializationFeature#WRAP_EXCEPTIONS}
3362 * does NOT result in wrapping of exception even if enabled)
3363 * @throws JsonParseException if underlying input contains invalid content
3364 * of type {@link JsonParser} supports (JSON for default case)
3365 * @throws JsonMappingException if the input JSON structure does not match structure
3366 * expected for result type (or has other mismatch issues)
3367 */
3368 @SuppressWarnings("unchecked")
3369 public <T> T readValue(File src, JavaType valueType)
3370 throws IOException, JsonParseException, JsonMappingException
3371 {
3372 _assertNotNull("src", src);
3373 return (T) _readMapAndClose(_jsonFactory.createParser(src), valueType);
3374 }
3375
3376 /**
3377 * Method to deserialize JSON content from given resource into given Java type.
3378 *<p>
3379 * NOTE: handling of {@link java.net.URL} is delegated to
3380 * {@link JsonFactory#createParser(java.net.URL)} and usually simply
3381 * calls {@link java.net.URL#openStream()}, meaning no special handling
3382 * is done. If different HTTP connection options are needed you will need
3383 * to create {@link java.io.InputStream} separately.
3384 *
3385 * @throws IOException if a low-level I/O problem (unexpected end-of-input,
3386 * network error) occurs (passed through as-is without additional wrapping -- note
3387 * that this is one case where {@link DeserializationFeature#WRAP_EXCEPTIONS}
3388 * does NOT result in wrapping of exception even if enabled)
3389 * @throws JsonParseException if underlying input contains invalid content
3390 * of type {@link JsonParser} supports (JSON for default case)
3391 * @throws JsonMappingException if the input JSON structure does not match structure
3392 * expected for result type (or has other mismatch issues)
3393 */
3394 @SuppressWarnings("unchecked")
3395 public <T> T readValue(URL src, Class<T> valueType)
3396 throws IOException, JsonParseException, JsonMappingException
3397 {
3398 _assertNotNull("src", src);
3399 return (T) _readMapAndClose(_jsonFactory.createParser(src), _typeFactory.constructType(valueType));
3400 }
3401
3402 /**
3403 * Same as {@link #readValue(java.net.URL, Class)} except that target specified by {@link TypeReference}.
3404 */
3405 @SuppressWarnings({ "unchecked" })
3406 public <T> T readValue(URL src, TypeReference<T> valueTypeRef)
3407 throws IOException, JsonParseException, JsonMappingException
3408 {
3409 _assertNotNull("src", src);
3410 return (T) _readMapAndClose(_jsonFactory.createParser(src), _typeFactory.constructType(valueTypeRef));
3411 }
3412
3413 /**
3414 * Same as {@link #readValue(java.net.URL, Class)} except that target specified by {@link JavaType}.
3415 */
3416 @SuppressWarnings("unchecked")
3417 public <T> T readValue(URL src, JavaType valueType)
3418 throws IOException, JsonParseException, JsonMappingException
3419 {
3420 _assertNotNull("src", src);
3421 return (T) _readMapAndClose(_jsonFactory.createParser(src), valueType);
3422 }
3423
3424 /**
3425 * Method to deserialize JSON content from given JSON content String.
3426 *
3427 * @throws JsonParseException if underlying input contains invalid content
3428 * of type {@link JsonParser} supports (JSON for default case)
3429 * @throws JsonMappingException if the input JSON structure does not match structure
3430 * expected for result type (or has other mismatch issues)
3431 */
3432 public <T> T readValue(String content, Class<T> valueType)
3433 throws JsonProcessingException, JsonMappingException
3434 {
3435 _assertNotNull("content", content);
3436 return readValue(content, _typeFactory.constructType(valueType));
3437 }
3438
3439 /**
3440 * Method to deserialize JSON content from given JSON content String.
3441 *
3442 * @throws JsonParseException if underlying input contains invalid content
3443 * of type {@link JsonParser} supports (JSON for default case)
3444 * @throws JsonMappingException if the input JSON structure does not match structure
3445 * expected for result type (or has other mismatch issues)
3446 */
3447 public <T> T readValue(String content, TypeReference<T> valueTypeRef)
3448 throws JsonProcessingException, JsonMappingException
3449 {
3450 _assertNotNull("content", content);
3451 return readValue(content, _typeFactory.constructType(valueTypeRef));
3452 }
3453
3454 /**
3455 * Method to deserialize JSON content from given JSON content String.
3456 *
3457 * @throws JsonParseException if underlying input contains invalid content
3458 * of type {@link JsonParser} supports (JSON for default case)
3459 * @throws JsonMappingException if the input JSON structure does not match structure
3460 * expected for result type (or has other mismatch issues)
3461 */
3462 @SuppressWarnings("unchecked")
3463 public <T> T readValue(String content, JavaType valueType)
3464 throws JsonProcessingException, JsonMappingException
3465 {
3466 _assertNotNull("content", content);
3467 try { // since 2.10 remove "impossible" IOException as per [databind#1675]
3468 return (T) _readMapAndClose(_jsonFactory.createParser(content), valueType);
3469 } catch (JsonProcessingException e) {
3470 throw e;
3471 } catch (IOException e) { // shouldn't really happen but being declared need to
3472 throw JsonMappingException.fromUnexpectedIOE(e);
3473 }
3474 }
3475
3476 @SuppressWarnings("unchecked")
3477 public <T> T readValue(Reader src, Class<T> valueType)
3478 throws IOException, JsonParseException, JsonMappingException
3479 {
3480 _assertNotNull("src", src);
3481 return (T) _readMapAndClose(_jsonFactory.createParser(src), _typeFactory.constructType(valueType));
3482 }
3483
3484 @SuppressWarnings({ "unchecked" })
3485 public <T> T readValue(Reader src, TypeReference<T> valueTypeRef)
3486 throws IOException, JsonParseException, JsonMappingException
3487 {
3488 _assertNotNull("src", src);
3489 return (T) _readMapAndClose(_jsonFactory.createParser(src), _typeFactory.constructType(valueTypeRef));
3490 }
3491
3492 @SuppressWarnings("unchecked")
3493 public <T> T readValue(Reader src, JavaType valueType)
3494 throws IOException, JsonParseException, JsonMappingException
3495 {
3496 _assertNotNull("src", src);
3497 return (T) _readMapAndClose(_jsonFactory.createParser(src), valueType);
3498 }
3499
3500 @SuppressWarnings("unchecked")
3501 public <T> T readValue(InputStream src, Class<T> valueType)
3502 throws IOException, JsonParseException, JsonMappingException
3503 {
3504 _assertNotNull("src", src);
3505 return (T) _readMapAndClose(_jsonFactory.createParser(src), _typeFactory.constructType(valueType));
3506 }
3507
3508 @SuppressWarnings({ "unchecked" })
3509 public <T> T readValue(InputStream src, TypeReference<T> valueTypeRef)
3510 throws IOException, JsonParseException, JsonMappingException
3511 {
3512 _assertNotNull("src", src);
3513 return (T) _readMapAndClose(_jsonFactory.createParser(src), _typeFactory.constructType(valueTypeRef));
3514 }
3515
3516 @SuppressWarnings("unchecked")
3517 public <T> T readValue(InputStream src, JavaType valueType)
3518 throws IOException, JsonParseException, JsonMappingException
3519 {
3520 _assertNotNull("src", src);
3521 return (T) _readMapAndClose(_jsonFactory.createParser(src), valueType);
3522 }
3523
3524 @SuppressWarnings("unchecked")
3525 public <T> T readValue(byte[] src, Class<T> valueType)
3526 throws IOException, JsonParseException, JsonMappingException
3527 {
3528 _assertNotNull("src", src);
3529 return (T) _readMapAndClose(_jsonFactory.createParser(src), _typeFactory.constructType(valueType));
3530 }
3531
3532 @SuppressWarnings("unchecked")
3533 public <T> T readValue(byte[] src, int offset, int len,
3534 Class<T> valueType)
3535 throws IOException, JsonParseException, JsonMappingException
3536 {
3537 _assertNotNull("src", src);
3538 return (T) _readMapAndClose(_jsonFactory.createParser(src, offset, len), _typeFactory.constructType(valueType));
3539 }
3540
3541 @SuppressWarnings({ "unchecked" })
3542 public <T> T readValue(byte[] src, TypeReference<T> valueTypeRef)
3543 throws IOException, JsonParseException, JsonMappingException
3544 {
3545 _assertNotNull("src", src);
3546 return (T) _readMapAndClose(_jsonFactory.createParser(src), _typeFactory.constructType(valueTypeRef));
3547 }
3548
3549 @SuppressWarnings({ "unchecked" })
3550 public <T> T readValue(byte[] src, int offset, int len,
3551 TypeReference<T> valueTypeRef)
3552 throws IOException, JsonParseException, JsonMappingException
3553 {
3554 _assertNotNull("src", src);
3555 return (T) _readMapAndClose(_jsonFactory.createParser(src, offset, len), _typeFactory.constructType(valueTypeRef));
3556 }
3557
3558 @SuppressWarnings("unchecked")
3559 public <T> T readValue(byte[] src, JavaType valueType)
3560 throws IOException, JsonParseException, JsonMappingException
3561 {
3562 _assertNotNull("src", src);
3563 return (T) _readMapAndClose(_jsonFactory.createParser(src), valueType);
3564 }
3565
3566 @SuppressWarnings("unchecked")
3567 public <T> T readValue(byte[] src, int offset, int len,
3568 JavaType valueType)
3569 throws IOException, JsonParseException, JsonMappingException
3570 {
3571 _assertNotNull("src", src);
3572 return (T) _readMapAndClose(_jsonFactory.createParser(src, offset, len), valueType);
3573 }
3574
3575 @SuppressWarnings("unchecked")
3576 public <T> T readValue(DataInput src, Class<T> valueType) throws IOException
3577 {
3578 _assertNotNull("src", src);
3579 return (T) _readMapAndClose(_jsonFactory.createParser(src),
3580 _typeFactory.constructType(valueType));
3581 }
3582
3583 @SuppressWarnings("unchecked")
3584 public <T> T readValue(DataInput src, JavaType valueType) throws IOException
3585 {
3586 _assertNotNull("src", src);
3587 return (T) _readMapAndClose(_jsonFactory.createParser(src), valueType);
3588 }
3589
3590 /*
3591 /**********************************************************
3592 /* Extended Public API: serialization
3593 /* (mapping from Java types to JSON)
3594 /**********************************************************
3595 */
3596
3597 /**
3598 * Method that can be used to serialize any Java value as
3599 * JSON output, written to File provided.
3600 */
3601 public void writeValue(File resultFile, Object value)
3602 throws IOException, JsonGenerationException, JsonMappingException
3603 {
3604 _writeValueAndClose(createGenerator(resultFile, JsonEncoding.UTF8), value);
3605 }
3606
3607 /**
3608 * Method that can be used to serialize any Java value as
3609 * JSON output, using output stream provided (using encoding
3610 * {@link JsonEncoding#UTF8}).
3611 *<p>
3612 * Note: method does not close the underlying stream explicitly
3613 * here; however, {@link JsonFactory} this mapper uses may choose
3614 * to close the stream depending on its settings (by default,
3615 * it will try to close it when {@link JsonGenerator} we construct
3616 * is closed).
3617 */
3618 public void writeValue(OutputStream out, Object value)
3619 throws IOException, JsonGenerationException, JsonMappingException
3620 {
3621 _writeValueAndClose(createGenerator(out, JsonEncoding.UTF8), value);
3622 }
3623
3624 /**
3625 * @since 2.8
3626 */
3627 public void writeValue(DataOutput out, Object value) throws IOException
3628 {
3629 _writeValueAndClose(createGenerator(out), value);
3630 }
3631
3632 /**
3633 * Method that can be used to serialize any Java value as
3634 * JSON output, using Writer provided.
3635 *<p>
3636 * Note: method does not close the underlying stream explicitly
3637 * here; however, {@link JsonFactory} this mapper uses may choose
3638 * to close the stream depending on its settings (by default,
3639 * it will try to close it when {@link JsonGenerator} we construct
3640 * is closed).
3641 */
3642 public void writeValue(Writer w, Object value)
3643 throws IOException, JsonGenerationException, JsonMappingException
3644 {
3645 _writeValueAndClose(createGenerator(w), value);
3646 }
3647
3648 /**
3649 * Method that can be used to serialize any Java value as
3650 * a String. Functionally equivalent to calling
3651 * {@link #writeValue(Writer,Object)} with {@link java.io.StringWriter}
3652 * and constructing String, but more efficient.
3653 *<p>
3654 * Note: prior to version 2.1, throws clause included {@link IOException}; 2.1 removed it.
3655 */
3656 @SuppressWarnings("resource")
3657 public String writeValueAsString(Object value)
3658 throws JsonProcessingException
3659 {
3660 // alas, we have to pull the recycler directly here...
3661 SegmentedStringWriter sw = new SegmentedStringWriter(_jsonFactory._getBufferRecycler());
3662 try {
3663 _writeValueAndClose(createGenerator(sw), value);
3664 } catch (JsonProcessingException e) {
3665 throw e;
3666 } catch (IOException e) { // shouldn't really happen, but is declared as possibility so:
3667 throw JsonMappingException.fromUnexpectedIOE(e);
3668 }
3669 return sw.getAndClear();
3670 }
3671
3672 /**
3673 * Method that can be used to serialize any Java value as
3674 * a byte array. Functionally equivalent to calling
3675 * {@link #writeValue(Writer,Object)} with {@link java.io.ByteArrayOutputStream}
3676 * and getting bytes, but more efficient.
3677 * Encoding used will be UTF-8.
3678 *<p>
3679 * Note: prior to version 2.1, throws clause included {@link IOException}; 2.1 removed it.
3680 */
3681 @SuppressWarnings("resource")
3682 public byte[] writeValueAsBytes(Object value)
3683 throws JsonProcessingException
3684 {
3685 ByteArrayBuilder bb = new ByteArrayBuilder(_jsonFactory._getBufferRecycler());
3686 try {
3687 _writeValueAndClose(createGenerator(bb, JsonEncoding.UTF8), value);
3688 } catch (JsonProcessingException e) { // to support [JACKSON-758]
3689 throw e;
3690 } catch (IOException e) { // shouldn't really happen, but is declared as possibility so:
3691 throw JsonMappingException.fromUnexpectedIOE(e);
3692 }
3693 byte[] result = bb.toByteArray();
3694 bb.release();
3695 return result;
3696 }
3697
3698 /*
3699 /**********************************************************
3700 /* Extended Public API: constructing ObjectWriters
3701 /* for more advanced configuration
3702 /**********************************************************
3703 */
3704
3705 /**
3706 * Convenience method for constructing {@link ObjectWriter}
3707 * with default settings.
3708 */
3709 public ObjectWriter writer() {
3710 return _newWriter(getSerializationConfig());
3711 }
3712
3713 /**
3714 * Factory method for constructing {@link ObjectWriter} with
3715 * specified feature enabled (compared to settings that this
3716 * mapper instance has).
3717 */
3718 public ObjectWriter writer(SerializationFeature feature) {
3719 return _newWriter(getSerializationConfig().with(feature));
3720 }
3721
3722 /**
3723 * Factory method for constructing {@link ObjectWriter} with
3724 * specified features enabled (compared to settings that this
3725 * mapper instance has).
3726 */
3727 public ObjectWriter writer(SerializationFeature first,
3728 SerializationFeature... other) {
3729 return _newWriter(getSerializationConfig().with(first, other));
3730 }
3731
3732 /**
3733 * Factory method for constructing {@link ObjectWriter} that will
3734 * serialize objects using specified {@link DateFormat}; or, if
3735 * null passed, using timestamp (64-bit number.
3736 */
3737 public ObjectWriter writer(DateFormat df) {
3738 return _newWriter(getSerializationConfig().with(df));
3739 }
3740
3741 /**
3742 * Factory method for constructing {@link ObjectWriter} that will
3743 * serialize objects using specified JSON View (filter).
3744 */
3745 public ObjectWriter writerWithView(Class<?> serializationView) {
3746 return _newWriter(getSerializationConfig().withView(serializationView));
3747 }
3748
3749 /**
3750 * Factory method for constructing {@link ObjectWriter} that will
3751 * serialize objects using specified root type, instead of actual
3752 * runtime type of value. Type must be a super-type of runtime type.
3753 *<p>
3754 * Main reason for using this method is performance, as writer is able
3755 * to pre-fetch serializer to use before write, and if writer is used
3756 * more than once this avoids addition per-value serializer lookups.
3757 *
3758 * @since 2.5
3759 */
3760 public ObjectWriter writerFor(Class<?> rootType) {
3761 return _newWriter(getSerializationConfig(),
3762 ((rootType == null) ? null :_typeFactory.constructType(rootType)),
3763 /*PrettyPrinter*/null);
3764 }
3765
3766 /**
3767 * Factory method for constructing {@link ObjectWriter} that will
3768 * serialize objects using specified root type, instead of actual
3769 * runtime type of value. Type must be a super-type of runtime type.
3770 *<p>
3771 * Main reason for using this method is performance, as writer is able
3772 * to pre-fetch serializer to use before write, and if writer is used
3773 * more than once this avoids addition per-value serializer lookups.
3774 *
3775 * @since 2.5
3776 */
3777 public ObjectWriter writerFor(TypeReference<?> rootType) {
3778 return _newWriter(getSerializationConfig(),
3779 ((rootType == null) ? null : _typeFactory.constructType(rootType)),
3780 /*PrettyPrinter*/null);
3781 }
3782
3783 /**
3784 * Factory method for constructing {@link ObjectWriter} that will
3785 * serialize objects using specified root type, instead of actual
3786 * runtime type of value. Type must be a super-type of runtime type.
3787 *<p>
3788 * Main reason for using this method is performance, as writer is able
3789 * to pre-fetch serializer to use before write, and if writer is used
3790 * more than once this avoids addition per-value serializer lookups.
3791 *
3792 * @since 2.5
3793 */
3794 public ObjectWriter writerFor(JavaType rootType) {
3795 return _newWriter(getSerializationConfig(), rootType, /*PrettyPrinter*/null);
3796 }
3797
3798 /**
3799 * Factory method for constructing {@link ObjectWriter} that will
3800 * serialize objects using specified pretty printer for indentation
3801 * (or if null, no pretty printer)
3802 */
3803 public ObjectWriter writer(PrettyPrinter pp) {
3804 if (pp == null) { // need to use a marker to indicate explicit disabling of pp
3805 pp = ObjectWriter.NULL_PRETTY_PRINTER;
3806 }
3807 return _newWriter(getSerializationConfig(), /*root type*/ null, pp);
3808 }
3809
3810 /**
3811 * Factory method for constructing {@link ObjectWriter} that will
3812 * serialize objects using the default pretty printer for indentation
3813 */
3814 public ObjectWriter writerWithDefaultPrettyPrinter() {
3815 SerializationConfig config = getSerializationConfig();
3816 return _newWriter(config,
3817 /*root type*/ null, config.getDefaultPrettyPrinter());
3818 }
3819
3820 /**
3821 * Factory method for constructing {@link ObjectWriter} that will
3822 * serialize objects using specified filter provider.
3823 */
3824 public ObjectWriter writer(FilterProvider filterProvider) {
3825 return _newWriter(getSerializationConfig().withFilters(filterProvider));
3826 }
3827
3828 /**
3829 * Factory method for constructing {@link ObjectWriter} that will
3830 * pass specific schema object to {@link JsonGenerator} used for
3831 * writing content.
3832 *
3833 * @param schema Schema to pass to generator
3834 */
3835 public ObjectWriter writer(FormatSchema schema) {
3836 _verifySchemaType(schema);
3837 return _newWriter(getSerializationConfig(), schema);
3838 }
3839
3840 /**
3841 * Factory method for constructing {@link ObjectWriter} that will
3842 * use specified Base64 encoding variant for Base64-encoded binary data.
3843 *
3844 * @since 2.1
3845 */
3846 public ObjectWriter writer(Base64Variant defaultBase64) {
3847 return _newWriter(getSerializationConfig().with(defaultBase64));
3848 }
3849
3850 /**
3851 * Factory method for constructing {@link ObjectReader} that will
3852 * use specified character escaping details for output.
3853 *
3854 * @since 2.3
3855 */
3856 public ObjectWriter writer(CharacterEscapes escapes) {
3857 return _newWriter(getSerializationConfig()).with(escapes);
3858 }
3859
3860 /**
3861 * Factory method for constructing {@link ObjectWriter} that will
3862 * use specified default attributes.
3863 *
3864 * @since 2.3
3865 */
3866 public ObjectWriter writer(ContextAttributes attrs) {
3867 return _newWriter(getSerializationConfig().with(attrs));
3868 }
3869
3870 /**
3871 * @deprecated Since 2.5, use {@link #writerFor(Class)} instead
3872 */
3873 @Deprecated
3874 public ObjectWriter writerWithType(Class<?> rootType) {
3875 return _newWriter(getSerializationConfig(),
3876 // 15-Mar-2013, tatu: Important! Indicate that static typing is needed:
3877 ((rootType == null) ? null :_typeFactory.constructType(rootType)),
3878 /*PrettyPrinter*/null);
3879 }
3880
3881 /**
3882 * @deprecated Since 2.5, use {@link #writerFor(TypeReference)} instead
3883 */
3884 @Deprecated
3885 public ObjectWriter writerWithType(TypeReference<?> rootType) {
3886 return _newWriter(getSerializationConfig(),
3887 // 15-Mar-2013, tatu: Important! Indicate that static typing is needed:
3888 ((rootType == null) ? null : _typeFactory.constructType(rootType)),
3889 /*PrettyPrinter*/null);
3890 }
3891
3892 /**
3893 * @deprecated Since 2.5, use {@link #writerFor(JavaType)} instead
3894 */
3895 @Deprecated
3896 public ObjectWriter writerWithType(JavaType rootType) {
3897 return _newWriter(getSerializationConfig(), rootType, /*PrettyPrinter*/null);
3898 }
3899
3900 /*
3901 /**********************************************************
3902 /* Extended Public API: constructing ObjectReaders
3903 /* for more advanced configuration
3904 /**********************************************************
3905 */
3906
3907 /**
3908 * Factory method for constructing {@link ObjectReader} with
3909 * default settings. Note that the resulting instance is NOT usable as is,
3910 * without defining expected value type.
3911 */
3912 public ObjectReader reader() {
3913 return _newReader(getDeserializationConfig()).with(_injectableValues);
3914 }
3915
3916 /**
3917 * Factory method for constructing {@link ObjectReader} with
3918 * specified feature enabled (compared to settings that this
3919 * mapper instance has).
3920 * Note that the resulting instance is NOT usable as is,
3921 * without defining expected value type.
3922 */
3923 public ObjectReader reader(DeserializationFeature feature) {
3924 return _newReader(getDeserializationConfig().with(feature));
3925 }
3926
3927 /**
3928 * Factory method for constructing {@link ObjectReader} with
3929 * specified features enabled (compared to settings that this
3930 * mapper instance has).
3931 * Note that the resulting instance is NOT usable as is,
3932 * without defining expected value type.
3933 */
3934 public ObjectReader reader(DeserializationFeature first,
3935 DeserializationFeature... other) {
3936 return _newReader(getDeserializationConfig().with(first, other));
3937 }
3938
3939 /**
3940 * Factory method for constructing {@link ObjectReader} that will
3941 * update given Object (usually Bean, but can be a Collection or Map
3942 * as well, but NOT an array) with JSON data. Deserialization occurs
3943 * normally except that the root-level value in JSON is not used for
3944 * instantiating a new object; instead give updateable object is used
3945 * as root.
3946 * Runtime type of value object is used for locating deserializer,
3947 * unless overridden by other factory methods of {@link ObjectReader}
3948 */
3949 public ObjectReader readerForUpdating(Object valueToUpdate) {
3950 JavaType t = _typeFactory.constructType(valueToUpdate.getClass());
3951 return _newReader(getDeserializationConfig(), t, valueToUpdate,
3952 null, _injectableValues);
3953 }
3954
3955 /**
3956 * Factory method for constructing {@link ObjectReader} that will
3957 * read or update instances of specified type
3958 *
3959 * @since 2.6
3960 */
3961 public ObjectReader readerFor(JavaType type) {
3962 return _newReader(getDeserializationConfig(), type, null,
3963 null, _injectableValues);
3964 }
3965
3966 /**
3967 * Factory method for constructing {@link ObjectReader} that will
3968 * read or update instances of specified type
3969 *
3970 * @since 2.6
3971 */
3972 public ObjectReader readerFor(Class<?> type) {
3973 return _newReader(getDeserializationConfig(), _typeFactory.constructType(type), null,
3974 null, _injectableValues);
3975 }
3976
3977 /**
3978 * Factory method for constructing {@link ObjectReader} that will
3979 * read or update instances of specified type
3980 *
3981 * @since 2.6
3982 */
3983 public ObjectReader readerFor(TypeReference<?> type) {
3984 return _newReader(getDeserializationConfig(), _typeFactory.constructType(type), null,
3985 null, _injectableValues);
3986 }
3987
3988 /**
3989 * Factory method for constructing {@link ObjectReader} that will
3990 * read values of a type {@code List<type>}.
3991 * Functionally same as:
3992 *<pre>
3993 * readerFor(type[].class);
3994 *</pre>
3995 *
3996 * @since 2.11
3997 */
3998 public ObjectReader readerForArrayOf(Class<?> type) {
3999 return _newReader(getDeserializationConfig(),
4000 _typeFactory.constructArrayType(type), null,
4001 null, _injectableValues);
4002 }
4003
4004 /**
4005 * Factory method for constructing {@link ObjectReader} that will
4006 * read or update instances of a type {@code List<type>}.
4007 * Functionally same as:
4008 *<pre>
4009 * readerFor(new TypeReference<List<type>>() { });
4010 *</pre>
4011 *
4012 * @since 2.11
4013 */
4014 public ObjectReader readerForListOf(Class<?> type) {
4015 return _newReader(getDeserializationConfig(),
4016 _typeFactory.constructCollectionType(List.class, type), null,
4017 null, _injectableValues);
4018 }
4019
4020 /**
4021 * Factory method for constructing {@link ObjectReader} that will
4022 * read or update instances of a type {@code Map<String, type>}
4023 * Functionally same as:
4024 *<pre>
4025 * readerFor(new TypeReference<Map<String, type>>() { });
4026 *</pre>
4027 *
4028 * @since 2.11
4029 */
4030 public ObjectReader readerForMapOf(Class<?> type) {
4031 return _newReader(getDeserializationConfig(),
4032 _typeFactory.constructMapType(Map.class, String.class, type), null,
4033 null, _injectableValues);
4034 }
4035
4036 /**
4037 * Factory method for constructing {@link ObjectReader} that will
4038 * use specified {@link JsonNodeFactory} for constructing JSON trees.
4039 */
4040 public ObjectReader reader(JsonNodeFactory f) {
4041 return _newReader(getDeserializationConfig()).with(f);
4042 }
4043
4044 /**
4045 * Factory method for constructing {@link ObjectReader} that will
4046 * pass specific schema object to {@link JsonParser} used for
4047 * reading content.
4048 *
4049 * @param schema Schema to pass to parser
4050 */
4051 public ObjectReader reader(FormatSchema schema) {
4052 _verifySchemaType(schema);
4053 return _newReader(getDeserializationConfig(), null, null,
4054 schema, _injectableValues);
4055 }
4056
4057 /**
4058 * Factory method for constructing {@link ObjectReader} that will
4059 * use specified injectable values.
4060 *
4061 * @param injectableValues Injectable values to use
4062 */
4063 public ObjectReader reader(InjectableValues injectableValues) {
4064 return _newReader(getDeserializationConfig(), null, null,
4065 null, injectableValues);
4066 }
4067
4068 /**
4069 * Factory method for constructing {@link ObjectReader} that will
4070 * deserialize objects using specified JSON View (filter).
4071 */
4072 public ObjectReader readerWithView(Class<?> view) {
4073 return _newReader(getDeserializationConfig().withView(view));
4074 }
4075
4076 /**
4077 * Factory method for constructing {@link ObjectReader} that will
4078 * use specified Base64 encoding variant for Base64-encoded binary data.
4079 *
4080 * @since 2.1
4081 */
4082 public ObjectReader reader(Base64Variant defaultBase64) {
4083 return _newReader(getDeserializationConfig().with(defaultBase64));
4084 }
4085
4086 /**
4087 * Factory method for constructing {@link ObjectReader} that will
4088 * use specified default attributes.
4089 *
4090 * @since 2.3
4091 */
4092 public ObjectReader reader(ContextAttributes attrs) {
4093 return _newReader(getDeserializationConfig().with(attrs));
4094 }
4095
4096 /**
4097 * @deprecated Since 2.5, use {@link #readerFor(JavaType)} instead
4098 */
4099 @Deprecated
4100 public ObjectReader reader(JavaType type) {
4101 return _newReader(getDeserializationConfig(), type, null,
4102 null, _injectableValues);
4103 }
4104
4105 /**
4106 * @deprecated Since 2.5, use {@link #readerFor(Class)} instead
4107 */
4108 @Deprecated
4109 public ObjectReader reader(Class<?> type) {
4110 return _newReader(getDeserializationConfig(), _typeFactory.constructType(type), null,
4111 null, _injectableValues);
4112 }
4113
4114 /**
4115 * @deprecated Since 2.5, use {@link #readerFor(TypeReference)} instead
4116 */
4117 @Deprecated
4118 public ObjectReader reader(TypeReference<?> type) {
4119 return _newReader(getDeserializationConfig(), _typeFactory.constructType(type), null,
4120 null, _injectableValues);
4121 }
4122
4123 /*
4124 /**********************************************************
4125 /* Extended Public API: convenience type conversion
4126 /**********************************************************
4127 */
4128
4129 /**
4130 * Convenience method for doing two-step conversion from given value, into
4131 * instance of given value type, by writing value into temporary buffer
4132 * and reading from the buffer into specified target type.
4133 *<p>
4134 * This method is functionally similar to first
4135 * serializing given value into JSON, and then binding JSON data into value
4136 * of given type, but should be more efficient since full serialization does
4137 * not (need to) occur.
4138 * However, same converters (serializers, deserializers) will be used as for
4139 * data binding, meaning same object mapper configuration works.
4140 *<p>
4141 * Note that behavior changed slightly between Jackson 2.9 and 2.10 so that
4142 * whereas earlier some optimizations were used to avoid write/read cycle
4143 * in case input was of target type, from 2.10 onwards full processing is
4144 * always performed. See
4145 * <a href="https://github.com/FasterXML/jackson-databind/issues/2220">databind#2220</a>
4146 * for full details of the change.
4147 *<p>
4148 * Further note that it is possible that in some cases behavior does differ
4149 * from full serialize-then-deserialize cycle: in most case differences are
4150 * unintentional (that is, flaws to fix) and should be reported, but
4151 * the behavior is not guaranteed to be 100% the same:
4152 * the goal is to allow efficient value conversions for structurally
4153 * compatible Objects, according to standard Jackson configuration.
4154 *<p>
4155 * Finally, this functionality is not designed to support "advanced" use
4156 * cases, such as conversion of polymorphic values, or cases where Object Identity
4157 * is used.
4158 *
4159 * @throws IllegalArgumentException If conversion fails due to incompatible type;
4160 * if so, root cause will contain underlying checked exception data binding
4161 * functionality threw
4162 */
4163 @SuppressWarnings("unchecked")
4164 public <T> T convertValue(Object fromValue, Class<T> toValueType)
4165 throws IllegalArgumentException
4166 {
4167 return (T) _convert(fromValue, _typeFactory.constructType(toValueType));
4168 }
4169
4170 /**
4171 * See {@link #convertValue(Object, Class)}
4172 */
4173 @SuppressWarnings("unchecked")
4174 public <T> T convertValue(Object fromValue, TypeReference<T> toValueTypeRef)
4175 throws IllegalArgumentException
4176 {
4177 return (T) _convert(fromValue, _typeFactory.constructType(toValueTypeRef));
4178 }
4179
4180 /**
4181 * See {@link #convertValue(Object, Class)}
4182 */
4183 @SuppressWarnings("unchecked")
4184 public <T> T convertValue(Object fromValue, JavaType toValueType)
4185 throws IllegalArgumentException
4186 {
4187 return (T) _convert(fromValue, toValueType);
4188 }
4189
4190 /**
4191 * Actual conversion implementation: instead of using existing read
4192 * and write methods, much of code is inlined. Reason for this is
4193 * that we must avoid root value wrapping/unwrapping both for efficiency and
4194 * for correctness. If root value wrapping/unwrapping is actually desired,
4195 * caller must use explicit <code>writeValue</code> and
4196 * <code>readValue</code> methods.
4197 */
4198 @SuppressWarnings("resource")
4199 protected Object _convert(Object fromValue, JavaType toValueType)
4200 throws IllegalArgumentException
4201 {
4202 // 25-Jan-2019, tatu: [databind#2220] Let's NOT try to short-circuit anything
4203
4204 // Then use TokenBuffer, which is a JsonGenerator:
4205 TokenBuffer buf = new TokenBuffer(this, false);
4206 if (isEnabled(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS)) {
4207 buf = buf.forceUseOfBigDecimal(true);
4208 }
4209 try {
4210 // inlined 'writeValue' with minor changes:
4211 // first: disable wrapping when writing
4212 SerializationConfig config = getSerializationConfig().without(SerializationFeature.WRAP_ROOT_VALUE);
4213 // no need to check for closing of TokenBuffer
4214 _serializerProvider(config).serializeValue(buf, fromValue);
4215
4216 // then matching read, inlined 'readValue' with minor mods:
4217 final JsonParser p = buf.asParser();
4218 Object result;
4219 // ok to pass in existing feature flags; unwrapping handled by mapper
4220 final DeserializationConfig deserConfig = getDeserializationConfig();
4221 JsonToken t = _initForReading(p, toValueType);
4222 if (t == JsonToken.VALUE_NULL) {
4223 DeserializationContext ctxt = createDeserializationContext(p, deserConfig);
4224 result = _findRootDeserializer(ctxt, toValueType).getNullValue(ctxt);
4225 } else if (t == JsonToken.END_ARRAY || t == JsonToken.END_OBJECT) {
4226 result = null;
4227 } else { // pointing to event other than null
4228 DeserializationContext ctxt = createDeserializationContext(p, deserConfig);
4229 JsonDeserializer<Object> deser = _findRootDeserializer(ctxt, toValueType);
4230 // note: no handling of unwrapping
4231 result = deser.deserialize(p, ctxt);
4232 }
4233 p.close();
4234 return result;
4235 } catch (IOException e) { // should not occur, no real i/o...
4236 throw new IllegalArgumentException(e.getMessage(), e);
4237 }
4238 }
4239
4240 /**
4241 * Convenience method similar to {@link #convertValue(Object, JavaType)} but one
4242 * in which
4243 *<p>
4244 * Implementation is approximately as follows:
4245 *<ol>
4246 * <li>Serialize `updateWithValue` into {@link TokenBuffer}</li>
4247 * <li>Construct {@link ObjectReader} with `valueToUpdate` (using {@link #readerForUpdating(Object)})
4248 * </li>
4249 * <li>Construct {@link JsonParser} (using {@link TokenBuffer#asParser()})
4250 * </li>
4251 * <li>Update using {@link ObjectReader#readValue(JsonParser)}.
4252 * </li>
4253 * <li>Return `valueToUpdate`
4254 * </li>
4255 *</ol>
4256 *<p>
4257 * Note that update is "shallow" in that only first level of properties (or, immediate contents
4258 * of container to update) are modified, unless properties themselves indicate that
4259 * merging should be applied for contents. Such merging can be specified using
4260 * annotations (see <code>JsonMerge</code>) as well as using "config overrides" (see
4261 * {@link #configOverride(Class)} and {@link #setDefaultMergeable(Boolean)}).
4262 *
4263 * @param valueToUpdate Object to update
4264 * @param overrides Object to conceptually serialize and merge into value to
4265 * update; can be thought of as a provider for overrides to apply.
4266 *
4267 * @return Either the first argument (`valueToUpdate`), if it is mutable; or a result of
4268 * creating new instance that is result of "merging" values (for example, "updating" a
4269 * Java array will create a new array)
4270 *
4271 * @throws JsonMappingException if there are structural incompatibilities that prevent update.
4272 *
4273 * @since 2.9
4274 */
4275 @SuppressWarnings("resource")
4276 public <T> T updateValue(T valueToUpdate, Object overrides)
4277 throws JsonMappingException
4278 {
4279 T result = valueToUpdate;
4280 if ((valueToUpdate != null) && (overrides != null)) {
4281 TokenBuffer buf = new TokenBuffer(this, false);
4282 if (isEnabled(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS)) {
4283 buf = buf.forceUseOfBigDecimal(true);
4284 }
4285 try {
4286 SerializationConfig config = getSerializationConfig().
4287 without(SerializationFeature.WRAP_ROOT_VALUE);
4288 _serializerProvider(config).serializeValue(buf, overrides);
4289 JsonParser p = buf.asParser();
4290 result = readerForUpdating(valueToUpdate).readValue(p);
4291 p.close();
4292 } catch (IOException e) { // should not occur, no real i/o...
4293 if (e instanceof JsonMappingException) {
4294 throw (JsonMappingException) e;
4295 }
4296 // 17-Mar-2017, tatu: Really ought not happen...
4297 throw JsonMappingException.fromUnexpectedIOE(e);
4298 }
4299 }
4300 return result;
4301 }
4302
4303 /*
4304 /**********************************************************
4305 /* Extended Public API: JSON Schema generation
4306 /**********************************************************
4307 */
4308
4309 /**
4310 * Generate <a href="http://json-schema.org/">Json-schema</a>
4311 * instance for specified class.
4312 *
4313 * @param t The class to generate schema for
4314 * @return Constructed JSON schema.
4315 *
4316 * @deprecated Since 2.6 use external JSON Schema generator (https://github.com/FasterXML/jackson-module-jsonSchema)
4317 * (which under the hood calls {@link #acceptJsonFormatVisitor(JavaType, JsonFormatVisitorWrapper)})
4318 */
4319 @Deprecated
4320 public com.fasterxml.jackson.databind.jsonschema.JsonSchema generateJsonSchema(Class<?> t)
4321 throws JsonMappingException {
4322 return _serializerProvider(getSerializationConfig()).generateJsonSchema(t);
4323 }
4324
4325 /**
4326 * Method for visiting type hierarchy for given type, using specified visitor.
4327 *<p>
4328 * This method can be used for things like
4329 * generating <a href="http://json-schema.org/">JSON Schema</a>
4330 * instance for specified type.
4331 *
4332 * @param type Type to generate schema for (possibly with generic signature)
4333 *
4334 * @since 2.1
4335 */
4336 public void acceptJsonFormatVisitor(Class<?> type, JsonFormatVisitorWrapper visitor)
4337 throws JsonMappingException
4338 {
4339 acceptJsonFormatVisitor(_typeFactory.constructType(type), visitor);
4340 }
4341
4342 /**
4343 * Method for visiting type hierarchy for given type, using specified visitor.
4344 * Visitation uses <code>Serializer</code> hierarchy and related properties
4345 *<p>
4346 * This method can be used for things like
4347 * generating <a href="http://json-schema.org/">JSON Schema</a>
4348 * instance for specified type.
4349 *
4350 * @param type Type to generate schema for (possibly with generic signature)
4351 *
4352 * @since 2.1
4353 */
4354 public void acceptJsonFormatVisitor(JavaType type, JsonFormatVisitorWrapper visitor)
4355 throws JsonMappingException
4356 {
4357 if (type == null) {
4358 throw new IllegalArgumentException("type must be provided");
4359 }
4360 _serializerProvider(getSerializationConfig()).acceptJsonFormatVisitor(type, visitor);
4361 }
4362
4363 /*
4364 /**********************************************************
4365 /* Internal factory methods for type ids, overridable
4366 /**********************************************************
4367 */
4368
4369 /**
4370 * Overridable factory method, separate to allow format-specific mappers (and specifically
4371 * XML-backed one, currently) to offer custom {@link TypeResolverBuilder} subtypes.
4372 *
4373 * @since 2.10
4374 */
4375 protected TypeResolverBuilder<?> _constructDefaultTypeResolverBuilder(DefaultTyping applicability,
4376 PolymorphicTypeValidator ptv) {
4377 return DefaultTypeResolverBuilder.construct(applicability, ptv);
4378 }
4379
4380 /*
4381 /**********************************************************
4382 /* Internal methods for serialization, overridable
4383 /**********************************************************
4384 */
4385
4386 /**
4387 * Overridable helper method used for constructing
4388 * {@link SerializerProvider} to use for serialization.
4389 */
4390 protected DefaultSerializerProvider _serializerProvider(SerializationConfig config) {
4391 return _serializerProvider.createInstance(config, _serializerFactory);
4392 }
4393
4394 /**
4395 * Method called to configure the generator as necessary and then
4396 * call write functionality
4397 *
4398 * @since 2.11.2
4399 */
4400 protected final void _writeValueAndClose(JsonGenerator g, Object value)
4401 throws IOException
4402 {
4403 SerializationConfig cfg = getSerializationConfig();
4404 if (cfg.isEnabled(SerializationFeature.CLOSE_CLOSEABLE) && (value instanceof Closeable)) {
4405 _writeCloseable(g, value, cfg);
4406 return;
4407 }
4408 try {
4409 _serializerProvider(cfg).serializeValue(g, value);
4410 } catch (Exception e) {
4411 ClassUtil.closeOnFailAndThrowAsIOE(g, e);
4412 return;
4413 }
4414 g.close();
4415 }
4416
4417 /**
4418 * Helper method used when value to serialize is {@link Closeable} and its <code>close()</code>
4419 * method is to be called right after serialization has been called
4420 */
4421 private final void _writeCloseable(JsonGenerator g, Object value, SerializationConfig cfg)
4422 throws IOException
4423 {
4424 Closeable toClose = (Closeable) value;
4425 try {
4426 _serializerProvider(cfg).serializeValue(g, value);
4427 Closeable tmpToClose = toClose;
4428 toClose = null;
4429 tmpToClose.close();
4430 } catch (Exception e) {
4431 ClassUtil.closeOnFailAndThrowAsIOE(g, toClose, e);
4432 return;
4433 }
4434 g.close();
4435 }
4436
4437 /**
4438 * Helper method used when value to serialize is {@link Closeable} and its <code>close()</code>
4439 * method is to be called right after serialization has been called
4440 */
4441 private final void _writeCloseableValue(JsonGenerator g, Object value, SerializationConfig cfg)
4442 throws IOException
4443 {
4444 Closeable toClose = (Closeable) value;
4445 try {
4446 _serializerProvider(cfg).serializeValue(g, value);
4447 if (cfg.isEnabled(SerializationFeature.FLUSH_AFTER_WRITE_VALUE)) {
4448 g.flush();
4449 }
4450 } catch (Exception e) {
4451 ClassUtil.closeOnFailAndThrowAsIOE(null, toClose, e);
4452 return;
4453 }
4454 toClose.close();
4455 }
4456
4457 /**
4458 * @deprecated Since 2.11.2 Use {@link #_writeValueAndClose} instead
4459 */
4460 @Deprecated // since 2.11.2 (to remove earliest from 2.13)
4461 protected final void _configAndWriteValue(JsonGenerator g, Object value) throws IOException {
4462 getSerializationConfig().initialize(g);
4463 _writeValueAndClose(g, value);
4464 }
4465
4466 /*
4467 /**********************************************************
4468 /* Internal methods for deserialization, overridable
4469 /**********************************************************
4470 */
4471
4472 /**
4473 * Actual implementation of value reading+binding operation.
4474 */
4475 protected Object _readValue(DeserializationConfig cfg, JsonParser p,
4476 JavaType valueType)
4477 throws IOException
4478 {
4479 /* First: may need to read the next token, to initialize
4480 * state (either before first read from parser, or after
4481 * previous token has been cleared)
4482 */
4483 Object result;
4484 JsonToken t = _initForReading(p, valueType);
4485 final DeserializationContext ctxt = createDeserializationContext(p, cfg);
4486 if (t == JsonToken.VALUE_NULL) {
4487 // Ask JsonDeserializer what 'null value' to use:
4488 result = _findRootDeserializer(ctxt, valueType).getNullValue(ctxt);
4489 } else if (t == JsonToken.END_ARRAY || t == JsonToken.END_OBJECT) {
4490 result = null;
4491 } else { // pointing to event other than null
4492 JsonDeserializer<Object> deser = _findRootDeserializer(ctxt, valueType);
4493 // ok, let's get the value
4494 if (cfg.useRootWrapping()) {
4495 result = _unwrapAndDeserialize(p, ctxt, cfg, valueType, deser);
4496 } else {
4497 result = deser.deserialize(p, ctxt);
4498 }
4499 }
4500 // Need to consume the token too
4501 p.clearCurrentToken();
4502 if (cfg.isEnabled(DeserializationFeature.FAIL_ON_TRAILING_TOKENS)) {
4503 _verifyNoTrailingTokens(p, ctxt, valueType);
4504 }
4505 return result;
4506 }
4507
4508 protected Object _readMapAndClose(JsonParser p0, JavaType valueType)
4509 throws IOException
4510 {
4511 try (JsonParser p = p0) {
4512 Object result;
4513 JsonToken t = _initForReading(p, valueType);
4514 final DeserializationConfig cfg = getDeserializationConfig();
4515 final DeserializationContext ctxt = createDeserializationContext(p, cfg);
4516 if (t == JsonToken.VALUE_NULL) {
4517 // Ask JsonDeserializer what 'null value' to use:
4518 result = _findRootDeserializer(ctxt, valueType).getNullValue(ctxt);
4519 } else if (t == JsonToken.END_ARRAY || t == JsonToken.END_OBJECT) {
4520 result = null;
4521 } else {
4522 JsonDeserializer<Object> deser = _findRootDeserializer(ctxt, valueType);
4523 if (cfg.useRootWrapping()) {
4524 result = _unwrapAndDeserialize(p, ctxt, cfg, valueType, deser);
4525 } else {
4526 result = deser.deserialize(p, ctxt);
4527 }
4528 ctxt.checkUnresolvedObjectId();
4529 }
4530 if (cfg.isEnabled(DeserializationFeature.FAIL_ON_TRAILING_TOKENS)) {
4531 _verifyNoTrailingTokens(p, ctxt, valueType);
4532 }
4533 return result;
4534 }
4535 }
4536
4537 /**
4538 * Similar to {@link #_readMapAndClose} but specialized for <code>JsonNode</code>
4539 * reading.
4540 *
4541 * @since 2.9
4542 */
4543 protected JsonNode _readTreeAndClose(JsonParser p0) throws IOException
4544 {
4545 try (JsonParser p = p0) {
4546 final JavaType valueType = constructType(JsonNode.class);
4547
4548 DeserializationConfig cfg = getDeserializationConfig();
4549 // 27-Oct-2016, tatu: Need to inline `_initForReading()` due to
4550 // special requirements by tree reading (no fail on eof)
4551
4552 cfg.initialize(p); // since 2.5
4553 JsonToken t = p.getCurrentToken();
4554 if (t == null) {
4555 t = p.nextToken();
4556 if (t == null) {
4557 // [databind#2211]: return `MissingNode` (supercedes [databind#1406] which dictated
4558 // returning `null`
4559 return cfg.getNodeFactory().missingNode();
4560 }
4561 }
4562 final boolean checkTrailing = cfg.isEnabled(DeserializationFeature.FAIL_ON_TRAILING_TOKENS);
4563 DeserializationContext ctxt;
4564 JsonNode resultNode;
4565
4566 if (t == JsonToken.VALUE_NULL) {
4567 resultNode = cfg.getNodeFactory().nullNode();
4568 if (!checkTrailing) {
4569 return resultNode;
4570 }
4571 ctxt = createDeserializationContext(p, cfg);
4572 } else {
4573 ctxt = createDeserializationContext(p, cfg);
4574 JsonDeserializer<Object> deser = _findRootDeserializer(ctxt, valueType);
4575 if (cfg.useRootWrapping()) {
4576 resultNode = (JsonNode) _unwrapAndDeserialize(p, ctxt, cfg, valueType, deser);
4577 } else {
4578 resultNode = (JsonNode) deser.deserialize(p, ctxt);
4579 }
4580 }
4581 if (checkTrailing) {
4582 _verifyNoTrailingTokens(p, ctxt, valueType);
4583 }
4584 // No ObjectIds so can ignore
4585 // ctxt.checkUnresolvedObjectId();
4586 return resultNode;
4587 }
4588 }
4589
4590 protected Object _unwrapAndDeserialize(JsonParser p, DeserializationContext ctxt,
4591 DeserializationConfig config,
4592 JavaType rootType, JsonDeserializer<Object> deser)
4593 throws IOException
4594 {
4595 PropertyName expRootName = config.findRootName(rootType);
4596 // 12-Jun-2015, tatu: Should try to support namespaces etc but...
4597 String expSimpleName = expRootName.getSimpleName();
4598 if (p.getCurrentToken() != JsonToken.START_OBJECT) {
4599 ctxt.reportWrongTokenException(rootType, JsonToken.START_OBJECT,
4600 "Current token not START_OBJECT (needed to unwrap root name '%s'), but %s",
4601 expSimpleName, p.getCurrentToken());
4602 }
4603 if (p.nextToken() != JsonToken.FIELD_NAME) {
4604 ctxt.reportWrongTokenException(rootType, JsonToken.FIELD_NAME,
4605 "Current token not FIELD_NAME (to contain expected root name '%s'), but %s",
4606 expSimpleName, p.getCurrentToken());
4607 }
4608 String actualName = p.getCurrentName();
4609 if (!expSimpleName.equals(actualName)) {
4610 ctxt.reportPropertyInputMismatch(rootType, actualName,
4611 "Root name '%s' does not match expected ('%s') for type %s",
4612 actualName, expSimpleName, rootType);
4613 }
4614 // ok, then move to value itself....
4615 p.nextToken();
4616 Object result = deser.deserialize(p, ctxt);
4617 // and last, verify that we now get matching END_OBJECT
4618 if (p.nextToken() != JsonToken.END_OBJECT) {
4619 ctxt.reportWrongTokenException(rootType, JsonToken.END_OBJECT,
4620 "Current token not END_OBJECT (to match wrapper object with root name '%s'), but %s",
4621 expSimpleName, p.getCurrentToken());
4622 }
4623 if (config.isEnabled(DeserializationFeature.FAIL_ON_TRAILING_TOKENS)) {
4624 _verifyNoTrailingTokens(p, ctxt, rootType);
4625 }
4626 return result;
4627 }
4628
4629 /**
4630 * Internal helper method called to create an instance of {@link DeserializationContext}
4631 * for deserializing a single root value.
4632 * Can be overridden if a custom context is needed.
4633 */
4634 protected DefaultDeserializationContext createDeserializationContext(JsonParser p,
4635 DeserializationConfig cfg) {
4636 return _deserializationContext.createInstance(cfg, p, _injectableValues);
4637 }
4638
4639 /**
4640 * Method called to ensure that given parser is ready for reading
4641 * content for data binding.
4642 *
4643 * @return First token to be used for data binding after this call:
4644 * can never be null as exception will be thrown if parser cannot
4645 * provide more tokens.
4646 *
4647 * @throws IOException if the underlying input source has problems during
4648 * parsing
4649 * @throws JsonParseException if parser has problems parsing content
4650 * @throws JsonMappingException if the parser does not have any more
4651 * content to map (note: Json "null" value is considered content;
4652 * enf-of-stream not)
4653 */
4654 protected JsonToken _initForReading(JsonParser p, JavaType targetType) throws IOException
4655 {
4656 _deserializationConfig.initialize(p); // since 2.5
4657
4658 // First: must point to a token; if not pointing to one, advance.
4659 // This occurs before first read from JsonParser, as well as
4660 // after clearing of current token.
4661 JsonToken t = p.getCurrentToken();
4662 if (t == null) {
4663 // and then we must get something...
4664 t = p.nextToken();
4665 if (t == null) {
4666 // Throw mapping exception, since it's failure to map,
4667 // not an actual parsing problem
4668 throw MismatchedInputException.from(p, targetType,
4669 "No content to map due to end-of-input");
4670 }
4671 }
4672 return t;
4673 }
4674
4675 @Deprecated // since 2.9, use method that takes JavaType too
4676 protected JsonToken _initForReading(JsonParser p) throws IOException {
4677 return _initForReading(p, null);
4678 }
4679
4680 /**
4681 * @since 2.9
4682 */
4683 protected final void _verifyNoTrailingTokens(JsonParser p, DeserializationContext ctxt,
4684 JavaType bindType)
4685 throws IOException
4686 {
4687 JsonToken t = p.nextToken();
4688 if (t != null) {
4689 Class<?> bt = ClassUtil.rawClass(bindType);
4690 ctxt.reportTrailingTokens(bt, p, t);
4691 }
4692 }
4693
4694 /*
4695 /**********************************************************
4696 /* Internal methods, other
4697 /**********************************************************
4698 */
4699
4700 /**
4701 * Method called to locate deserializer for the passed root-level value.
4702 */
4703 protected JsonDeserializer<Object> _findRootDeserializer(DeserializationContext ctxt,
4704 JavaType valueType)
4705 throws JsonMappingException
4706 {
4707 // First: have we already seen it?
4708 JsonDeserializer<Object> deser = _rootDeserializers.get(valueType);
4709 if (deser != null) {
4710 return deser;
4711 }
4712 // Nope: need to ask provider to resolve it
4713 deser = ctxt.findRootValueDeserializer(valueType);
4714 if (deser == null) { // can this happen?
4715 return ctxt.reportBadDefinition(valueType,
4716 "Cannot find a deserializer for type "+valueType);
4717 }
4718 _rootDeserializers.put(valueType, deser);
4719 return deser;
4720 }
4721
4722 /**
4723 * @since 2.2
4724 */
4725 protected void _verifySchemaType(FormatSchema schema)
4726 {
4727 if (schema != null) {
4728 if (!_jsonFactory.canUseSchema(schema)) {
4729 throw new IllegalArgumentException("Cannot use FormatSchema of type "+schema.getClass().getName()
4730 +" for format "+_jsonFactory.getFormatName());
4731 }
4732 }
4733 }
4734
4735 protected final void _assertNotNull(String paramName, Object src) {
4736 if (src == null) {
4737 throw new IllegalArgumentException(String.format("argument \"%s\" is null", paramName));
4738 }
4739 }
4740 }
4741