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