1 package com.fasterxml.jackson.databind;
2
3 import java.io.*;
4 import java.net.URL;
5 import java.util.*;
6 import java.util.concurrent.ConcurrentHashMap;
7
8 import com.fasterxml.jackson.core.*;
9 import com.fasterxml.jackson.core.filter.FilteringParserDelegate;
10 import com.fasterxml.jackson.core.filter.JsonPointerBasedFilter;
11 import com.fasterxml.jackson.core.filter.TokenFilter;
12 import com.fasterxml.jackson.core.type.ResolvedType;
13 import com.fasterxml.jackson.core.type.TypeReference;
14
15 import com.fasterxml.jackson.databind.cfg.ContextAttributes;
16 import com.fasterxml.jackson.databind.deser.DataFormatReaders;
17 import com.fasterxml.jackson.databind.deser.DefaultDeserializationContext;
18 import com.fasterxml.jackson.databind.deser.DeserializationProblemHandler;
19 import com.fasterxml.jackson.databind.node.JsonNodeFactory;
20 import com.fasterxml.jackson.databind.node.TreeTraversingParser;
21 import com.fasterxml.jackson.databind.type.TypeFactory;
22 import com.fasterxml.jackson.databind.util.ClassUtil;
23
24 /**
25 * Builder object that can be used for per-serialization configuration of
26 * deserialization parameters, such as root type to use or object
27 * to update (instead of constructing new instance).
28 *<p>
29 * Uses "mutant factory" pattern so that instances are immutable
30 * (and thus fully thread-safe with no external synchronization);
31 * new instances are constructed for different configurations.
32 * Instances are initially constructed by {@link ObjectMapper} and can be
33 * reused, shared, cached; both because of thread-safety and because
34 * instances are relatively light-weight.
35 *<p>
36 * NOTE: this class is NOT meant as sub-classable (with Jackson 2.8 and
37 * above) by users. It is left as non-final mostly to allow frameworks
38 * that require bytecode generation for proxying and similar use cases,
39 * but there is no expecation that functionality should be extended
40 * by sub-classing.
41 */
42 public class ObjectReader
43 extends ObjectCodec
44 implements Versioned, java.io.Serializable // since 2.1
45 {
46 private static final long serialVersionUID = 2L; // since 2.9
47
48 /*
49 /**********************************************************
50 /* Immutable configuration from ObjectMapper
51 /**********************************************************
52 */
53
54 /**
55 * General serialization configuration settings; while immutable,
56 * can use copy-constructor to create modified instances as necessary.
57 */
58 protected final DeserializationConfig _config;
59
60 /**
61 * Blueprint instance of deserialization context; used for creating
62 * actual instance when needed.
63 */
64 protected final DefaultDeserializationContext _context;
65
66 /**
67 * Factory used for constructing {@link JsonGenerator}s
68 */
69 protected final JsonFactory _parserFactory;
70
71 /**
72 * Flag that indicates whether root values are expected to be unwrapped or not
73 */
74 protected final boolean _unwrapRoot;
75
76 /**
77 * Filter to be consider for JsonParser.
78 * Default value to be null as filter not considered.
79 */
80 private final TokenFilter _filter;
81
82 /*
83 /**********************************************************
84 /* Configuration that can be changed during building
85 /**********************************************************
86 */
87
88 /**
89 * Declared type of value to instantiate during deserialization.
90 * Defines which deserializer to use; as well as base type of instance
91 * to construct if an updatable value is not configured to be used
92 * (subject to changes by embedded type information, for polymorphic
93 * types). If {@link #_valueToUpdate} is non-null, only used for
94 * locating deserializer.
95 */
96 protected final JavaType _valueType;
97
98 /**
99 * We may pre-fetch deserializer as soon as {@link #_valueType}
100 * is known, and if so, reuse it afterwards.
101 * This allows avoiding further deserializer lookups and increases
102 * performance a bit on cases where readers are reused.
103 *
104 * @since 2.1
105 */
106 protected final JsonDeserializer<Object> _rootDeserializer;
107
108 /**
109 * Instance to update with data binding; if any. If null,
110 * a new instance is created, if non-null, properties of
111 * this value object will be updated instead.
112 * Note that value can be of almost any type, except not
113 * {@link com.fasterxml.jackson.databind.type.ArrayType}; array
114 * types cannot be modified because array size is immutable.
115 */
116 protected final Object _valueToUpdate;
117
118 /**
119 * When using data format that uses a schema, schema is passed
120 * to parser.
121 */
122 protected final FormatSchema _schema;
123
124 /**
125 * Values that can be injected during deserialization, if any.
126 */
127 protected final InjectableValues _injectableValues;
128
129 /**
130 * Optional detector used for auto-detecting data format that byte-based
131 * input uses.
132 *<p>
133 * NOTE: If defined non-null, <code>readValue()</code> methods that take
134 * {@link Reader} or {@link String} input <b>will fail with exception</b>,
135 * because format-detection only works on byte-sources. Also, if format
136 * cannot be detect reliably (as per detector settings),
137 * a {@link JsonParseException} will be thrown).
138 *
139 * @since 2.1
140 */
141 protected final DataFormatReaders _dataFormatReaders;
142
143 /*
144 /**********************************************************
145 /* Caching
146 /**********************************************************
147 */
148
149 /**
150 * Root-level cached deserializers.
151 * Passed by {@link ObjectMapper}, shared with it.
152 */
153 final protected ConcurrentHashMap<JavaType, JsonDeserializer<Object>> _rootDeserializers;
154
155 /**
156 * Lazily resolved {@link JavaType} for {@link JsonNode}
157 */
158 protected transient JavaType _jsonNodeType;
159
160 /*
161 /**********************************************************
162 /* Life-cycle, construction
163 /**********************************************************
164 */
165
166 /**
167 * Constructor used by {@link ObjectMapper} for initial instantiation
168 */
169 protected ObjectReader(ObjectMapper mapper, DeserializationConfig config) {
170 this(mapper, config, null, null, null, null);
171 }
172
173 /**
174 * Constructor called when a root deserializer should be fetched based
175 * on other configuration.
176 */
177 protected ObjectReader(ObjectMapper mapper, DeserializationConfig config,
178 JavaType valueType, Object valueToUpdate,
179 FormatSchema schema, InjectableValues injectableValues)
180 {
181 _config = config;
182 _context = mapper._deserializationContext;
183 _rootDeserializers = mapper._rootDeserializers;
184 _parserFactory = mapper._jsonFactory;
185 _valueType = valueType;
186 _valueToUpdate = valueToUpdate;
187 _schema = schema;
188 _injectableValues = injectableValues;
189 _unwrapRoot = config.useRootWrapping();
190
191 _rootDeserializer = _prefetchRootDeserializer(valueType);
192 _dataFormatReaders = null;
193 _filter = null;
194 }
195
196 /**
197 * Copy constructor used for building variations.
198 */
199 protected ObjectReader(ObjectReader base, DeserializationConfig config,
200 JavaType valueType, JsonDeserializer<Object> rootDeser, Object valueToUpdate,
201 FormatSchema schema, InjectableValues injectableValues,
202 DataFormatReaders dataFormatReaders)
203 {
204 _config = config;
205 _context = base._context;
206
207 _rootDeserializers = base._rootDeserializers;
208 _parserFactory = base._parserFactory;
209
210 _valueType = valueType;
211 _rootDeserializer = rootDeser;
212 _valueToUpdate = valueToUpdate;
213 _schema = schema;
214 _injectableValues = injectableValues;
215 _unwrapRoot = config.useRootWrapping();
216 _dataFormatReaders = dataFormatReaders;
217 _filter = base._filter;
218 }
219
220 /**
221 * Copy constructor used when modifying simple feature flags
222 */
223 protected ObjectReader(ObjectReader base, DeserializationConfig config)
224 {
225 _config = config;
226 _context = base._context;
227
228 _rootDeserializers = base._rootDeserializers;
229 _parserFactory = base._parserFactory;
230
231 _valueType = base._valueType;
232 _rootDeserializer = base._rootDeserializer;
233 _valueToUpdate = base._valueToUpdate;
234 _schema = base._schema;
235 _injectableValues = base._injectableValues;
236 _unwrapRoot = config.useRootWrapping();
237 _dataFormatReaders = base._dataFormatReaders;
238 _filter = base._filter;
239 }
240
241 protected ObjectReader(ObjectReader base, JsonFactory f)
242 {
243 // may need to override ordering, based on data format capabilities
244 _config = base._config
245 .with(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, f.requiresPropertyOrdering());
246 _context = base._context;
247
248 _rootDeserializers = base._rootDeserializers;
249 _parserFactory = f;
250
251 _valueType = base._valueType;
252 _rootDeserializer = base._rootDeserializer;
253 _valueToUpdate = base._valueToUpdate;
254 _schema = base._schema;
255 _injectableValues = base._injectableValues;
256 _unwrapRoot = base._unwrapRoot;
257 _dataFormatReaders = base._dataFormatReaders;
258 _filter = base._filter;
259 }
260
261 protected ObjectReader(ObjectReader base, TokenFilter filter) {
262 _config = base._config;
263 _context = base._context;
264 _rootDeserializers = base._rootDeserializers;
265 _parserFactory = base._parserFactory;
266 _valueType = base._valueType;
267 _rootDeserializer = base._rootDeserializer;
268 _valueToUpdate = base._valueToUpdate;
269 _schema = base._schema;
270 _injectableValues = base._injectableValues;
271 _unwrapRoot = base._unwrapRoot;
272 _dataFormatReaders = base._dataFormatReaders;
273 _filter = filter;
274 }
275
276 /**
277 * Method that will return version information stored in and read from jar
278 * that contains this class.
279 */
280 @Override
281 public Version version() {
282 return com.fasterxml.jackson.databind.cfg.PackageVersion.VERSION;
283 }
284
285 /*
286 /**********************************************************
287 /* Helper methods used internally for invoking constructors
288 /* Need to be overridden if sub-classing (not recommended)
289 /* is used.
290 /**********************************************************
291 */
292
293 /**
294 * Overridable factory method called by various "withXxx()" methods
295 *
296 * @since 2.5
297 */
298 protected ObjectReader _new(ObjectReader base, JsonFactory f) {
299 return new ObjectReader(base, f);
300 }
301
302 /**
303 * Overridable factory method called by various "withXxx()" methods
304 *
305 * @since 2.5
306 */
307 protected ObjectReader _new(ObjectReader base, DeserializationConfig config) {
308 return new ObjectReader(base, config);
309 }
310
311 /**
312 * Overridable factory method called by various "withXxx()" methods
313 *
314 * @since 2.5
315 */
316 protected ObjectReader _new(ObjectReader base, DeserializationConfig config,
317 JavaType valueType, JsonDeserializer<Object> rootDeser, Object valueToUpdate,
318 FormatSchema schema, InjectableValues injectableValues,
319 DataFormatReaders dataFormatReaders) {
320 return new ObjectReader(base, config, valueType, rootDeser, valueToUpdate,
321 schema, injectableValues, dataFormatReaders);
322 }
323
324 /**
325 * Factory method used to create {@link MappingIterator} instances;
326 * either default, or custom subtype.
327 *
328 * @since 2.5
329 */
330 protected <T> MappingIterator<T> _newIterator(JsonParser p, DeserializationContext ctxt,
331 JsonDeserializer<?> deser, boolean parserManaged)
332 {
333 return new MappingIterator<T>(_valueType, p, ctxt,
334 deser, parserManaged, _valueToUpdate);
335 }
336
337 /*
338 /**********************************************************
339 /* Methods for initializing parser instance to use
340 /**********************************************************
341 */
342
343 protected JsonToken _initForReading(DeserializationContext ctxt, JsonParser p)
344 throws IOException
345 {
346 if (_schema != null) {
347 p.setSchema(_schema);
348 }
349 _config.initialize(p); // since 2.5
350
351 /* First: must point to a token; if not pointing to one, advance.
352 * This occurs before first read from JsonParser, as well as
353 * after clearing of current token.
354 */
355 JsonToken t = p.getCurrentToken();
356 if (t == null) { // and then we must get something...
357 t = p.nextToken();
358 if (t == null) {
359 // Throw mapping exception, since it's failure to map, not an actual parsing problem
360 ctxt.reportInputMismatch(_valueType,
361 "No content to map due to end-of-input");
362 }
363 }
364 return t;
365 }
366
367 /**
368 * Alternative to {@link #_initForReading} used in cases where reading
369 * of multiple values means that we may or may not want to advance the stream,
370 * but need to do other initialization.
371 *<p>
372 * Base implementation only sets configured {@link FormatSchema}, if any, on parser.
373 *
374 * @since 2.8
375 */
376 protected void _initForMultiRead(DeserializationContext ctxt, JsonParser p)
377 throws IOException
378 {
379 if (_schema != null) {
380 p.setSchema(_schema);
381 }
382 _config.initialize(p);
383 }
384
385 /*
386 /**********************************************************
387 /* Life-cycle, fluent factory methods for DeserializationFeatures
388 /**********************************************************
389 */
390
391 /**
392 * Method for constructing a new reader instance that is configured
393 * with specified feature enabled.
394 */
395 public ObjectReader with(DeserializationFeature feature) {
396 return _with(_config.with(feature));
397 }
398
399 /**
400 * Method for constructing a new reader instance that is configured
401 * with specified features enabled.
402 */
403 public ObjectReader with(DeserializationFeature first,
404 DeserializationFeature... other)
405 {
406 return _with(_config.with(first, other));
407 }
408
409 /**
410 * Method for constructing a new reader instance that is configured
411 * with specified features enabled.
412 */
413 public ObjectReader withFeatures(DeserializationFeature... features) {
414 return _with(_config.withFeatures(features));
415 }
416
417 /**
418 * Method for constructing a new reader instance that is configured
419 * with specified feature disabled.
420 */
421 public ObjectReader without(DeserializationFeature feature) {
422 return _with(_config.without(feature));
423 }
424
425 /**
426 * Method for constructing a new reader instance that is configured
427 * with specified features disabled.
428 */
429 public ObjectReader without(DeserializationFeature first,
430 DeserializationFeature... other) {
431 return _with(_config.without(first, other));
432 }
433
434 /**
435 * Method for constructing a new reader instance that is configured
436 * with specified features disabled.
437 */
438 public ObjectReader withoutFeatures(DeserializationFeature... features) {
439 return _with(_config.withoutFeatures(features));
440 }
441
442 /*
443 /**********************************************************
444 /* Life-cycle, fluent factory methods for JsonParser.Features
445 /* (to be deprecated in 2.12?)
446 /**********************************************************
447 */
448
449 /**
450 * Method for constructing a new reader instance that is configured
451 * with specified feature enabled.
452 *
453 * @param feature Feature to enable
454 *
455 * @return Reader instance with specified feature enabled
456 */
457 public ObjectReader with(JsonParser.Feature feature) {
458 return _with(_config.with(feature));
459 }
460
461 /**
462 * Method for constructing a new reader instance that is configured
463 * with specified features enabled.
464 *
465 * @param features Features to enable
466 *
467 * @return Reader instance with specified features enabled
468 */
469 public ObjectReader withFeatures(JsonParser.Feature... features) {
470 return _with(_config.withFeatures(features));
471 }
472
473 /**
474 * Method for constructing a new reader instance that is configured
475 * with specified feature disabled.
476 *
477 * @param feature Feature to disable
478 *
479 * @return Reader instance with specified feature disabled
480 */
481 public ObjectReader without(JsonParser.Feature feature) {
482 return _with(_config.without(feature));
483 }
484
485 /**
486 * Method for constructing a new reader instance that is configured
487 * with specified features disabled.
488 *
489 * @param features Features to disable
490 *
491 * @return Reader instance with specified features disabled
492 */
493 public ObjectReader withoutFeatures(JsonParser.Feature... features) {
494 return _with(_config.withoutFeatures(features));
495 }
496
497 /*
498 /**********************************************************************
499 /* Life-cycle, fluent factory methods for StreamReadFeatures (added in 2.11)
500 /**********************************************************************
501 */
502
503 /**
504 * Method for constructing a new reader instance that is configured
505 * with specified feature enabled.
506 *
507 * @return Reader instance with specified feature enabled
508 *
509 * @since 2.11
510 */
511 public ObjectReader with(StreamReadFeature feature) {
512 return _with(_config.with(feature.mappedFeature()));
513 }
514
515 /**
516 * Method for constructing a new reader instance that is configured
517 * with specified feature disabled.
518 *
519 * @return Reader instance with specified feature enabled
520 *
521 * @since 2.11
522 */
523 public ObjectReader without(StreamReadFeature feature) {
524 return _with(_config.without(feature.mappedFeature()));
525 }
526
527 /*
528 /**********************************************************
529 /* Life-cycle, fluent factory methods for FormatFeature (2.7)
530 /**********************************************************
531 */
532
533 /**
534 * Method for constructing a new reader instance that is configured
535 * with specified feature enabled.
536 *
537 * @since 2.7
538 */
539 public ObjectReader with(FormatFeature feature) {
540 return _with(_config.with(feature));
541 }
542
543 /**
544 * Method for constructing a new reader instance that is configured
545 * with specified features enabled.
546 *
547 * @since 2.7
548 */
549 public ObjectReader withFeatures(FormatFeature... features) {
550 return _with(_config.withFeatures(features));
551 }
552
553 /**
554 * Method for constructing a new reader instance that is configured
555 * with specified feature disabled.
556 *
557 * @since 2.7
558 */
559 public ObjectReader without(FormatFeature feature) {
560 return _with(_config.without(feature));
561 }
562
563 /**
564 * Method for constructing a new reader instance that is configured
565 * with specified features disabled.
566 *
567 * @since 2.7
568 */
569 public ObjectReader withoutFeatures(FormatFeature... features) {
570 return _with(_config.withoutFeatures(features));
571 }
572
573 /*
574 /**********************************************************
575 /* Life-cycle, fluent factory methods, other
576 /**********************************************************
577 */
578
579 /**
580 * Convenience method to bind from {@link JsonPointer}.
581 * {@link JsonPointerBasedFilter} is registered and will be used for parsing later.
582 * @since 2.6
583 */
584 public ObjectReader at(final String pointerExpr) {
585 _assertNotNull("pointerExpr", pointerExpr);
586 return new ObjectReader(this, new JsonPointerBasedFilter(pointerExpr));
587 }
588
589 /**
590 * Convenience method to bind from {@link JsonPointer}
591 * {@link JsonPointerBasedFilter} is registered and will be used for parsing later.
592 * @since 2.6
593 */
594 public ObjectReader at(final JsonPointer pointer) {
595 _assertNotNull("pointer", pointer);
596 return new ObjectReader(this, new JsonPointerBasedFilter(pointer));
597 }
598
599 /**
600 * Mutant factory method that will construct a new instance that has
601 * specified underlying {@link DeserializationConfig}.
602 *<p>
603 * NOTE: use of this method is not recommended, as there are many other
604 * re-configuration methods available.
605 */
606 public ObjectReader with(DeserializationConfig config) {
607 return _with(config);
608 }
609
610 /**
611 * Method for constructing a new instance with configuration that uses
612 * passed {@link InjectableValues} to provide injectable values.
613 *<p>
614 * Note that the method does NOT change state of this reader, but
615 * rather construct and returns a newly configured instance.
616 */
617 public ObjectReader with(InjectableValues injectableValues)
618 {
619 if (_injectableValues == injectableValues) {
620 return this;
621 }
622 return _new(this, _config,
623 _valueType, _rootDeserializer, _valueToUpdate,
624 _schema, injectableValues, _dataFormatReaders);
625 }
626
627 /**
628 * Method for constructing a new reader instance with configuration that uses
629 * passed {@link JsonNodeFactory} for constructing {@link JsonNode}
630 * instances.
631 *<p>
632 * Note that the method does NOT change state of this reader, but
633 * rather construct and returns a newly configured instance.
634 */
635 public ObjectReader with(JsonNodeFactory f) {
636 return _with(_config.with(f));
637 }
638
639 /**
640 * Method for constructing a new reader instance with configuration that uses
641 * passed {@link JsonFactory} for constructing underlying Readers.
642 *<p>
643 * NOTE: only factories that <b>DO NOT REQUIRE SPECIAL MAPPERS</b>
644 * (that is, ones that return <code>false</code> for
645 * {@link JsonFactory#requiresCustomCodec()}) can be used: trying
646 * to use one that requires custom codec will throw exception
647 *
648 * @since 2.1
649 */
650 public ObjectReader with(JsonFactory f) {
651 if (f == _parserFactory) {
652 return this;
653 }
654 ObjectReader r = _new(this, f);
655 // Also, try re-linking, if possible...
656 if (f.getCodec() == null) {
657 f.setCodec(r);
658 }
659 return r;
660 }
661
662 /**
663 * Method for constructing a new instance with configuration that
664 * specifies what root name to expect for "root name unwrapping".
665 * See {@link DeserializationConfig#withRootName(String)} for
666 * details.
667 *<p>
668 * Note that the method does NOT change state of this reader, but
669 * rather construct and returns a newly configured instance.
670 */
671 public ObjectReader withRootName(String rootName) {
672 return _with(_config.withRootName(rootName));
673 }
674
675 /**
676 * @since 2.6
677 */
678 public ObjectReader withRootName(PropertyName rootName) {
679 return _with(_config.withRootName(rootName));
680 }
681
682 /**
683 * Convenience method that is same as calling:
684 *<code>
685 * withRootName("")
686 *</code>
687 * which will forcibly prevent use of root name wrapping when writing
688 * values with this {@link ObjectReader}.
689 *
690 * @since 2.6
691 */
692 public ObjectReader withoutRootName() {
693 return _with(_config.withRootName(PropertyName.NO_NAME));
694 }
695
696 /**
697 * Method for constructing a new instance with configuration that
698 * passes specified {@link FormatSchema} to {@link JsonParser} that
699 * is constructed for parsing content.
700 *<p>
701 * Note that the method does NOT change state of this reader, but
702 * rather construct and returns a newly configured instance.
703 */
704 public ObjectReader with(FormatSchema schema)
705 {
706 if (_schema == schema) {
707 return this;
708 }
709 _verifySchemaType(schema);
710 return _new(this, _config, _valueType, _rootDeserializer, _valueToUpdate,
711 schema, _injectableValues, _dataFormatReaders);
712 }
713
714 /**
715 * Method for constructing a new reader instance that is configured
716 * to data bind into specified type.
717 *<p>
718 * Note that the method does NOT change state of this reader, but
719 * rather construct and returns a newly configured instance.
720 *
721 * @since 2.5
722 */
723 public ObjectReader forType(JavaType valueType)
724 {
725 if (valueType != null && valueType.equals(_valueType)) {
726 return this;
727 }
728 JsonDeserializer<Object> rootDeser = _prefetchRootDeserializer(valueType);
729 // type is stored here, no need to make a copy of config
730 DataFormatReaders det = _dataFormatReaders;
731 if (det != null) {
732 det = det.withType(valueType);
733 }
734 return _new(this, _config, valueType, rootDeser,
735 _valueToUpdate, _schema, _injectableValues, det);
736 }
737
738 /**
739 * Method for constructing a new reader instance that is configured
740 * to data bind into specified type.
741 *<p>
742 * Note that the method does NOT change state of this reader, but
743 * rather construct and returns a newly configured instance.
744 *
745 * @since 2.5
746 */
747 public ObjectReader forType(Class<?> valueType) {
748 return forType(_config.constructType(valueType));
749 }
750
751 /**
752 * Method for constructing a new reader instance that is configured
753 * to data bind into specified type.
754 *<p>
755 * Note that the method does NOT change state of this reader, but
756 * rather construct and returns a newly configured instance.
757 *
758 * @since 2.5
759 */
760 public ObjectReader forType(TypeReference<?> valueTypeRef) {
761 return forType(_config.getTypeFactory().constructType(valueTypeRef.getType()));
762 }
763
764 /**
765 * @deprecated since 2.5 Use {@link #forType(JavaType)} instead
766 */
767 @Deprecated
768 public ObjectReader withType(JavaType valueType) {
769 return forType(valueType);
770 }
771
772 /**
773 * @deprecated since 2.5 Use {@link #forType(Class)} instead
774 */
775 @Deprecated
776 public ObjectReader withType(Class<?> valueType) {
777 return forType(_config.constructType(valueType));
778 }
779
780 /**
781 * @deprecated since 2.5 Use {@link #forType(Class)} instead
782 */
783 @Deprecated
784 public ObjectReader withType(java.lang.reflect.Type valueType) {
785 return forType(_config.getTypeFactory().constructType(valueType));
786 }
787
788 /**
789 * @deprecated since 2.5 Use {@link #forType(TypeReference)} instead
790 */
791 @Deprecated
792 public ObjectReader withType(TypeReference<?> valueTypeRef) {
793 return forType(_config.getTypeFactory().constructType(valueTypeRef.getType()));
794 }
795
796 /**
797 * Method for constructing a new instance with configuration that
798 * updates passed Object (as root value), instead of constructing
799 * a new value.
800 *<p>
801 * Note that the method does NOT change state of this reader, but
802 * rather construct and returns a newly configured instance.
803 */
804 public ObjectReader withValueToUpdate(Object value)
805 {
806 if (value == _valueToUpdate) return this;
807 if (value == null) {
808 // 18-Oct-2016, tatu: Actually, should be allowed, to remove value
809 // to update, if any
810 return _new(this, _config, _valueType, _rootDeserializer, null,
811 _schema, _injectableValues, _dataFormatReaders);
812 }
813 JavaType t;
814
815 /* no real benefit from pre-fetching, as updating readers are much
816 * less likely to be reused, and value type may also be forced
817 * with a later chained call...
818 */
819 if (_valueType == null) {
820 t = _config.constructType(value.getClass());
821 } else {
822 t = _valueType;
823 }
824 return _new(this, _config, t, _rootDeserializer, value,
825 _schema, _injectableValues, _dataFormatReaders);
826 }
827
828 /**
829 * Method for constructing a new instance with configuration that
830 * uses specified View for filtering.
831 *<p>
832 * Note that the method does NOT change state of this reader, but
833 * rather construct and returns a newly configured instance.
834 */
835 public ObjectReader withView(Class<?> activeView) {
836 return _with(_config.withView(activeView));
837 }
838
839 public ObjectReader with(Locale l) {
840 return _with(_config.with(l));
841 }
842
843 public ObjectReader with(TimeZone tz) {
844 return _with(_config.with(tz));
845 }
846
847 public ObjectReader withHandler(DeserializationProblemHandler h) {
848 return _with(_config.withHandler(h));
849 }
850
851 public ObjectReader with(Base64Variant defaultBase64) {
852 return _with(_config.with(defaultBase64));
853 }
854
855 /**
856 * Fluent factory method for constructing a reader that will try to
857 * auto-detect underlying data format, using specified list of
858 * {@link JsonFactory} instances, and default {@link DataFormatReaders} settings
859 * (for customized {@link DataFormatReaders}, you can construct instance yourself).
860 * to construct appropriate {@link JsonParser} for actual parsing.
861 *<p>
862 * Note: since format detection only works with byte sources, it is possible to
863 * get a failure from some 'readValue()' methods. Also, if input cannot be reliably
864 * (enough) detected as one of specified types, an exception will be thrown.
865 *<p>
866 * Note: not all {@link JsonFactory} types can be passed: specifically, ones that
867 * require "custom codec" (like XML factory) will not work. Instead, use
868 * method that takes {@link ObjectReader} instances instead of factories.
869 *
870 * @param readers Data formats accepted, in decreasing order of priority (that is,
871 * matches checked in listed order, first match wins)
872 *
873 * @return Newly configured writer instance
874 *
875 * @since 2.1
876 */
877 public ObjectReader withFormatDetection(ObjectReader... readers) {
878 return withFormatDetection(new DataFormatReaders(readers));
879 }
880
881 /**
882 * Fluent factory method for constructing a reader that will try to
883 * auto-detect underlying data format, using specified
884 * {@link DataFormatReaders}.
885 *<p>
886 * NOTE: since format detection only works with byte sources, it is possible to
887 * get a failure from some 'readValue()' methods. Also, if input cannot be reliably
888 * (enough) detected as one of specified types, an exception will be thrown.
889 *
890 * @param readers DataFormatReaders to use for detecting underlying format.
891 *
892 * @return Newly configured writer instance
893 *
894 * @since 2.1
895 */
896 public ObjectReader withFormatDetection(DataFormatReaders readers) {
897 return _new(this, _config, _valueType, _rootDeserializer, _valueToUpdate,
898 _schema, _injectableValues, readers);
899 }
900
901 /**
902 * @since 2.3
903 */
904 public ObjectReader with(ContextAttributes attrs) {
905 return _with(_config.with(attrs));
906 }
907
908 /**
909 * @since 2.3
910 */
911 public ObjectReader withAttributes(Map<?,?> attrs) {
912 return _with(_config.withAttributes(attrs));
913 }
914
915 /**
916 * @since 2.3
917 */
918 public ObjectReader withAttribute(Object key, Object value) {
919 return _with( _config.withAttribute(key, value));
920 }
921
922 /**
923 * @since 2.3
924 */
925 public ObjectReader withoutAttribute(Object key) {
926 return _with(_config.withoutAttribute(key));
927 }
928
929 /*
930 /**********************************************************
931 /* Overridable factory methods may override
932 /**********************************************************
933 */
934
935 protected ObjectReader _with(DeserializationConfig newConfig) {
936 if (newConfig == _config) {
937 return this;
938 }
939 ObjectReader r = _new(this, newConfig);
940 if (_dataFormatReaders != null) {
941 r = r.withFormatDetection(_dataFormatReaders.with(newConfig));
942 }
943 return r;
944 }
945
946 /*
947 /**********************************************************
948 /* Simple accessors
949 /**********************************************************
950 */
951
952 public boolean isEnabled(DeserializationFeature f) {
953 return _config.isEnabled(f);
954 }
955
956 public boolean isEnabled(MapperFeature f) {
957 return _config.isEnabled(f);
958 }
959
960 public boolean isEnabled(JsonParser.Feature f) {
961 return _config.isEnabled(f, _parserFactory);
962 }
963
964 /**
965 * @since 2.11
966 */
967 public boolean isEnabled(StreamReadFeature f) {
968 return _config.isEnabled(f.mappedFeature(), _parserFactory);
969 }
970
971 /**
972 * @since 2.2
973 */
974 public DeserializationConfig getConfig() {
975 return _config;
976 }
977
978 /**
979 * @since 2.1
980 */
981 @Override
982 public JsonFactory getFactory() {
983 return _parserFactory;
984 }
985
986 public TypeFactory getTypeFactory() {
987 return _config.getTypeFactory();
988 }
989
990 /**
991 * @since 2.3
992 */
993 public ContextAttributes getAttributes() {
994 return _config.getAttributes();
995 }
996
997 /**
998 * @since 2.6
999 */
1000 public InjectableValues getInjectableValues() {
1001 return _injectableValues;
1002 }
1003
1004 /**
1005 * @since 2.10
1006 */
1007 public JavaType getValueType() {
1008 return _valueType;
1009 }
1010
1011 /*
1012 /**********************************************************
1013 /* Factory methods for creating JsonParsers (added in 2.11)
1014 /**********************************************************
1015 */
1016
1017 /**
1018 * Factory method for constructing properly initialized {@link JsonParser}
1019 * to read content from specified {@link File}.
1020 * Parser is not managed (or "owned") by ObjectReader: caller is responsible
1021 * for properly closing it once content reading is complete.
1022 *
1023 * @since 2.11
1024 */
1025 public JsonParser createParser(File src) throws IOException {
1026 _assertNotNull("src", src);
1027 JsonParser p = _parserFactory.createParser(src);
1028 _config.initialize(p);
1029 return p;
1030 }
1031
1032 /**
1033 * Factory method for constructing properly initialized {@link JsonParser}
1034 * to read content from specified {@link File}.
1035 * Parser is not managed (or "owned") by ObjectReader: caller is responsible
1036 * for properly closing it once content reading is complete.
1037 *
1038 * @since 2.11
1039 */
1040 public JsonParser createParser(URL src) throws IOException {
1041 _assertNotNull("src", src);
1042 JsonParser p = _parserFactory.createParser(src);
1043 _config.initialize(p);
1044 return p;
1045 }
1046
1047 /**
1048 * Factory method for constructing properly initialized {@link JsonParser}
1049 * to read content using specified {@link InputStream}.
1050 * Parser is not managed (or "owned") by ObjectReader: caller is responsible
1051 * for properly closing it once content reading is complete.
1052 *
1053 * @since 2.11
1054 */
1055 public JsonParser createParser(InputStream in) throws IOException {
1056 _assertNotNull("in", in);
1057 JsonParser p = _parserFactory.createParser(in);
1058 _config.initialize(p);
1059 return p;
1060 }
1061
1062 /**
1063 * Factory method for constructing properly initialized {@link JsonParser}
1064 * to read content using specified {@link Reader}.
1065 * Parser is not managed (or "owned") by ObjectReader: caller is responsible
1066 * for properly closing it once content reading is complete.
1067 *
1068 * @since 2.11
1069 */
1070 public JsonParser createParser(Reader r) throws IOException {
1071 _assertNotNull("r", r);
1072 JsonParser p = _parserFactory.createParser(r);
1073 _config.initialize(p);
1074 return p;
1075 }
1076
1077 /**
1078 * Factory method for constructing properly initialized {@link JsonParser}
1079 * to read content from specified byte array.
1080 * Parser is not managed (or "owned") by ObjectReader: caller is responsible
1081 * for properly closing it once content reading is complete.
1082 *
1083 * @since 2.11
1084 */
1085 public JsonParser createParser(byte[] content) throws IOException {
1086 _assertNotNull("content", content);
1087 JsonParser p = _parserFactory.createParser(content);
1088 _config.initialize(p);
1089 return p;
1090 }
1091
1092 /**
1093 * Factory method for constructing properly initialized {@link JsonParser}
1094 * to read content from specified byte array.
1095 * Parser is not managed (or "owned") by ObjectReader: caller is responsible
1096 * for properly closing it once content reading is complete.
1097 *
1098 * @since 2.11
1099 */
1100 public JsonParser createParser(byte[] content, int offset, int len) throws IOException {
1101 _assertNotNull("content", content);
1102 JsonParser p = _parserFactory.createParser(content, offset, len);
1103 _config.initialize(p);
1104 return p;
1105 }
1106
1107 /**
1108 * Factory method for constructing properly initialized {@link JsonParser}
1109 * to read content from specified String.
1110 * Parser is not managed (or "owned") by ObjectReader: caller is responsible
1111 * for properly closing it once content reading is complete.
1112 *
1113 * @since 2.11
1114 */
1115 public JsonParser createParser(String content) throws IOException {
1116 _assertNotNull("content", content);
1117 JsonParser p = _parserFactory.createParser(content);
1118 _config.initialize(p);
1119 return p;
1120 }
1121
1122 /**
1123 * Factory method for constructing properly initialized {@link JsonParser}
1124 * to read content from specified character array
1125 * Parser is not managed (or "owned") by ObjectReader: caller is responsible
1126 * for properly closing it once content reading is complete.
1127 *
1128 * @since 2.11
1129 */
1130 public JsonParser createParser(char[] content) throws IOException {
1131 _assertNotNull("content", content);
1132 JsonParser p = _parserFactory.createParser(content);
1133 _config.initialize(p);
1134 return p;
1135 }
1136
1137 /**
1138 * Factory method for constructing properly initialized {@link JsonParser}
1139 * to read content from specified character array.
1140 * Parser is not managed (or "owned") by ObjectReader: caller is responsible
1141 * for properly closing it once content reading is complete.
1142 *
1143 * @since 2.11
1144 */
1145 public JsonParser createParser(char[] content, int offset, int len) throws IOException {
1146 _assertNotNull("content", content);
1147 JsonParser p = _parserFactory.createParser(content, offset, len);
1148 _config.initialize(p);
1149 return p;
1150 }
1151
1152 /**
1153 * Factory method for constructing properly initialized {@link JsonParser}
1154 * to read content using specified {@link DataInput}.
1155 * Parser is not managed (or "owned") by ObjectReader: caller is responsible
1156 * for properly closing it once content reading is complete.
1157 *
1158 * @since 2.11
1159 */
1160 public JsonParser createParser(DataInput content) throws IOException {
1161 _assertNotNull("content", content);
1162 JsonParser p = _parserFactory.createParser(content);
1163 _config.initialize(p);
1164 return p;
1165 }
1166
1167 /**
1168 * Factory method for constructing properly initialized {@link JsonParser}
1169 * to read content using non-blocking (asynchronous) mode.
1170 * Parser is not managed (or "owned") by ObjectReader: caller is responsible
1171 * for properly closing it once content reading is complete.
1172 *
1173 * @since 2.11
1174 */
1175 public JsonParser createNonBlockingByteArrayParser() throws IOException {
1176 JsonParser p = _parserFactory.createNonBlockingByteArrayParser();
1177 _config.initialize(p);
1178 return p;
1179 }
1180
1181 /*
1182 /**********************************************************
1183 /* Deserialization methods; basic ones to support ObjectCodec first
1184 /* (ones that take JsonParser)
1185 /**********************************************************
1186 */
1187
1188 /**
1189 * Method that binds content read using given parser, using
1190 * configuration of this reader, including expected result type.
1191 * Value return is either newly constructed, or root value that
1192 * was specified with {@link #withValueToUpdate(Object)}.
1193 *<p>
1194 * NOTE: this method never tries to auto-detect format, since actual
1195 * (data-format specific) parser is given.
1196 */
1197 @SuppressWarnings("unchecked")
1198 public <T> T readValue(JsonParser p) throws IOException
1199 {
1200 _assertNotNull("p", p);
1201 return (T) _bind(p, _valueToUpdate);
1202 }
1203
1204 /**
1205 * Convenience method that binds content read using given parser, using
1206 * configuration of this reader, except that expected value type
1207 * is specified with the call (instead of currently configured root type).
1208 * Value return is either newly constructed, or root value that
1209 * was specified with {@link #withValueToUpdate(Object)}.
1210 *<p>
1211 * NOTE: this method never tries to auto-detect format, since actual
1212 * (data-format specific) parser is given.
1213 */
1214 @SuppressWarnings("unchecked")
1215 @Override
1216 public <T> T readValue(JsonParser p, Class<T> valueType) throws IOException
1217 {
1218 _assertNotNull("p", p);
1219 return (T) forType(valueType).readValue(p);
1220 }
1221
1222 /**
1223 * Convenience method that binds content read using given parser, using
1224 * configuration of this reader, except that expected value type
1225 * is specified with the call (instead of currently configured root type).
1226 * Value return is either newly constructed, or root value that
1227 * was specified with {@link #withValueToUpdate(Object)}.
1228 *<p>
1229 * NOTE: this method never tries to auto-detect format, since actual
1230 * (data-format specific) parser is given.
1231 */
1232 @SuppressWarnings("unchecked")
1233 @Override
1234 public <T> T readValue(JsonParser p, TypeReference<T> valueTypeRef) throws IOException
1235 {
1236 _assertNotNull("p", p);
1237 return (T) forType(valueTypeRef).readValue(p);
1238 }
1239
1240 /**
1241 * Convenience method that binds content read using given parser, using
1242 * configuration of this reader, except that expected value type
1243 * is specified with the call (instead of currently configured root type).
1244 * Value return is either newly constructed, or root value that
1245 * was specified with {@link #withValueToUpdate(Object)}.
1246 *<p>
1247 * NOTE: this method never tries to auto-detect format, since actual
1248 * (data-format specific) parser is given.
1249 */
1250 @Override
1251 @SuppressWarnings("unchecked")
1252 public <T> T readValue(JsonParser p, ResolvedType valueType) throws IOException {
1253 _assertNotNull("p", p);
1254 return (T) forType((JavaType)valueType).readValue(p);
1255 }
1256
1257 /**
1258 * Type-safe overloaded method, basically alias for {@link #readValue(JsonParser, ResolvedType)}.
1259 *<p>
1260 * NOTE: this method never tries to auto-detect format, since actual
1261 * (data-format specific) parser is given.
1262 */
1263 @SuppressWarnings("unchecked")
1264 public <T> T readValue(JsonParser p, JavaType valueType) throws IOException {
1265 _assertNotNull("p", p);
1266 return (T) forType(valueType).readValue(p);
1267 }
1268
1269 /**
1270 * Convenience method that is equivalent to:
1271 *<pre>
1272 * withType(valueType).readValues(p);
1273 *</pre>
1274 *<p>
1275 * Method reads a sequence of Objects from parser stream.
1276 * Sequence can be either root-level "unwrapped" sequence (without surrounding
1277 * JSON array), or a sequence contained in a JSON Array.
1278 * In either case {@link JsonParser} <b>MUST</b> point to the first token of
1279 * the first element, OR not point to any token (in which case it is advanced
1280 * to the next token). This means, specifically, that for wrapped sequences,
1281 * parser MUST NOT point to the surrounding <code>START_ARRAY</code> (one that
1282 * contains values to read) but rather to the token following it which is the first
1283 * token of the first value to read.
1284 *<p>
1285 * NOTE: this method never tries to auto-detect format, since actual
1286 * (data-format specific) parser is given.
1287 */
1288 @Override
1289 public <T> Iterator<T> readValues(JsonParser p, Class<T> valueType) throws IOException {
1290 _assertNotNull("p", p);
1291 return forType(valueType).readValues(p);
1292 }
1293
1294 /**
1295 * Convenience method that is equivalent to:
1296 *<pre>
1297 * withType(valueTypeRef).readValues(p);
1298 *</pre>
1299 *<p>
1300 * Method reads a sequence of Objects from parser stream.
1301 * Sequence can be either root-level "unwrapped" sequence (without surrounding
1302 * JSON array), or a sequence contained in a JSON Array.
1303 * In either case {@link JsonParser} <b>MUST</b> point to the first token of
1304 * the first element, OR not point to any token (in which case it is advanced
1305 * to the next token). This means, specifically, that for wrapped sequences,
1306 * parser MUST NOT point to the surrounding <code>START_ARRAY</code> (one that
1307 * contains values to read) but rather to the token following it which is the first
1308 * token of the first value to read.
1309 *<p>
1310 * NOTE: this method never tries to auto-detect format, since actual
1311 * (data-format specific) parser is given.
1312 */
1313 @Override
1314 public <T> Iterator<T> readValues(JsonParser p, TypeReference<T> valueTypeRef) throws IOException {
1315 _assertNotNull("p", p);
1316 return forType(valueTypeRef).readValues(p);
1317 }
1318
1319 /**
1320 * Convenience method that is equivalent to:
1321 *<pre>
1322 * withType(valueType).readValues(p);
1323 *</pre>
1324 *<p>
1325 * Method reads a sequence of Objects from parser stream.
1326 * Sequence can be either root-level "unwrapped" sequence (without surrounding
1327 * JSON array), or a sequence contained in a JSON Array.
1328 * In either case {@link JsonParser} <b>MUST</b> point to the first token of
1329 * the first element, OR not point to any token (in which case it is advanced
1330 * to the next token). This means, specifically, that for wrapped sequences,
1331 * parser MUST NOT point to the surrounding <code>START_ARRAY</code> (one that
1332 * contains values to read) but rather to the token following it which is the first
1333 * token of the first value to read.
1334 *<p>
1335 * NOTE: this method never tries to auto-detect format, since actual
1336 * (data-format specific) parser is given.
1337 */
1338 @Override
1339 public <T> Iterator<T> readValues(JsonParser p, ResolvedType valueType) throws IOException {
1340 _assertNotNull("p", p);
1341 return readValues(p, (JavaType) valueType);
1342 }
1343
1344 /**
1345 * Convenience method that is equivalent to:
1346 *<pre>
1347 * withType(valueType).readValues(p);
1348 *</pre>
1349 *<p>
1350 * Method reads a sequence of Objects from parser stream.
1351 * Sequence can be either root-level "unwrapped" sequence (without surrounding
1352 * JSON array), or a sequence contained in a JSON Array.
1353 * In either case {@link JsonParser} <b>MUST</b> point to the first token of
1354 * the first element, OR not point to any token (in which case it is advanced
1355 * to the next token). This means, specifically, that for wrapped sequences,
1356 * parser MUST NOT point to the surrounding <code>START_ARRAY</code> (one that
1357 * contains values to read) but rather to the token following it which is the first
1358 * token of the first value to read.
1359 *<p>
1360 * NOTE: this method never tries to auto-detect format, since actual
1361 * (data-format specific) parser is given.
1362 */
1363 public <T> Iterator<T> readValues(JsonParser p, JavaType valueType) throws IOException {
1364 _assertNotNull("p", p);
1365 return forType(valueType).readValues(p);
1366 }
1367
1368 /*
1369 /**********************************************************
1370 /* TreeCodec impl
1371 /**********************************************************
1372 */
1373
1374 @Override
1375 public JsonNode createArrayNode() {
1376 return _config.getNodeFactory().arrayNode();
1377 }
1378
1379 @Override
1380 public JsonNode createObjectNode() {
1381 return _config.getNodeFactory().objectNode();
1382 }
1383
1384 @Override // since 2.10
1385 public JsonNode missingNode() {
1386 return _config.getNodeFactory().missingNode();
1387 }
1388
1389 @Override // since 2.10
1390 public JsonNode nullNode() {
1391 return _config.getNodeFactory().nullNode();
1392 }
1393
1394 @Override
1395 public JsonParser treeAsTokens(TreeNode n) {
1396 _assertNotNull("n", n);
1397 // 05-Dec-2017, tatu: Important! Must clear "valueToUpdate" since we do not
1398 // want update to be applied here, as a side effect
1399 ObjectReader codec = withValueToUpdate(null);
1400 return new TreeTraversingParser((JsonNode) n, codec);
1401 }
1402
1403 /**
1404 * Convenience method that binds content read using given parser, using
1405 * configuration of this reader, except that content is bound as
1406 * JSON tree instead of configured root value type.
1407 * Returns {@link JsonNode} that represents the root of the resulting tree, if there
1408 * was content to read, or {@code null} if no more content is accessible
1409 * via passed {@link JsonParser}.
1410 *<p>
1411 * NOTE! Behavior with end-of-input (no more content) differs between this
1412 * {@code readTree} method, and all other methods that take input source: latter
1413 * will return "missing node", NOT {@code null}
1414 *<p>
1415 * Note: if an object was specified with {@link #withValueToUpdate}, it
1416 * will be ignored.
1417 *<p>
1418 * NOTE: this method never tries to auto-detect format, since actual
1419 * (data-format specific) parser is given.
1420 */
1421 @SuppressWarnings("unchecked")
1422 @Override
1423 public <T extends TreeNode> T readTree(JsonParser p) throws IOException {
1424 _assertNotNull("p", p);
1425 return (T) _bindAsTreeOrNull(p);
1426 }
1427
1428 @Override
1429 public void writeTree(JsonGenerator g, TreeNode rootNode) {
1430 throw new UnsupportedOperationException();
1431 }
1432
1433 /*
1434 /**********************************************************
1435 /* Deserialization methods; others similar to what ObjectMapper has
1436 /**********************************************************
1437 */
1438
1439 /**
1440 * Method that binds content read from given input source,
1441 * using configuration of this reader.
1442 * Value return is either newly constructed, or root value that
1443 * was specified with {@link #withValueToUpdate(Object)}.
1444 *
1445 * @param src Source to read content from
1446 */
1447 @SuppressWarnings("unchecked")
1448 public <T> T readValue(InputStream src) throws IOException
1449 {
1450 if (_dataFormatReaders != null) {
1451 return (T) _detectBindAndClose(_dataFormatReaders.findFormat(src), false);
1452 }
1453 return (T) _bindAndClose(_considerFilter(createParser(src), false));
1454 }
1455
1456 /**
1457 * Same as {@link #readValue(InputStream)} except that target value type
1458 * overridden as {@code valueType}
1459 *
1460 * @param src Source to read content from
1461 * @param valueType Target type to bind content to
1462 *
1463 * @since 2.11
1464 */
1465 @SuppressWarnings("unchecked")
1466 public <T> T readValue(InputStream src, Class<T> valueType) throws IOException
1467 {
1468 return (T) forType(valueType).readValue(src);
1469 }
1470
1471 /**
1472 * Method that binds content read from given input source,
1473 * using configuration of this reader.
1474 * Value return is either newly constructed, or root value that
1475 * was specified with {@link #withValueToUpdate(Object)}.
1476 *
1477 * @param src Source to read content from
1478 */
1479 @SuppressWarnings("unchecked")
1480 public <T> T readValue(Reader src) throws IOException
1481 {
1482 if (_dataFormatReaders != null) {
1483 _reportUndetectableSource(src);
1484 }
1485 return (T) _bindAndClose(_considerFilter(createParser(src), false));
1486 }
1487
1488 /**
1489 * Same as {@link #readValue(Reader)} except that target value type
1490 * overridden as {@code valueType}
1491 *
1492 * @param src Source to read content from
1493 * @param valueType Target type to bind content to
1494 *
1495 * @since 2.11
1496 */
1497 @SuppressWarnings("unchecked")
1498 public <T> T readValue(Reader src, Class<T> valueType) throws IOException
1499 {
1500 return (T) forType(valueType).readValue(src);
1501 }
1502
1503 /**
1504 * Method that binds content read from given JSON string,
1505 * using configuration of this reader.
1506 * Value return is either newly constructed, or root value that
1507 * was specified with {@link #withValueToUpdate(Object)}.
1508 *
1509 * @param src String that contains content to read
1510 */
1511 @SuppressWarnings("unchecked")
1512 public <T> T readValue(String src) throws JsonProcessingException, JsonMappingException
1513 {
1514 if (_dataFormatReaders != null) {
1515 _reportUndetectableSource(src);
1516 }
1517 try { // since 2.10 remove "impossible" IOException as per [databind#1675]
1518 return (T) _bindAndClose(_considerFilter(createParser(src), false));
1519 } catch (JsonProcessingException e) {
1520 throw e;
1521 } catch (IOException e) { // shouldn't really happen but being declared need to
1522 throw JsonMappingException.fromUnexpectedIOE(e);
1523 }
1524 }
1525
1526 /**
1527 * Same as {@link #readValue(String)} except that target value type
1528 * overridden as {@code valueType}
1529 *
1530 * @param src String that contains content to read
1531 * @param valueType Target type to bind content to
1532 *
1533 * @since 2.11
1534 */
1535 @SuppressWarnings("unchecked")
1536 public <T> T readValue(String src, Class<T> valueType) throws IOException
1537 {
1538 return (T) forType(valueType).readValue(src);
1539 }
1540
1541 /**
1542 * Method that binds content read from given byte array,
1543 * using configuration of this reader.
1544 * Value return is either newly constructed, or root value that
1545 * was specified with {@link #withValueToUpdate(Object)}.
1546 *
1547 * @param content Byte array that contains encoded content to read
1548 */
1549 @SuppressWarnings("unchecked")
1550 public <T> T readValue(byte[] content) throws IOException
1551 {
1552 if (_dataFormatReaders != null) {
1553 return (T) _detectBindAndClose(content, 0, content.length);
1554 }
1555 return (T) _bindAndClose(_considerFilter(createParser(content), false));
1556 }
1557
1558 /**
1559 * Same as {@link #readValue(byte[])} except that target value type
1560 * overridden as {@code valueType}
1561 *
1562 * @param content Byte array that contains encoded content to read
1563 * @param valueType Target type to bind content to
1564 *
1565 * @since 2.11
1566 */
1567 @SuppressWarnings("unchecked")
1568 public <T> T readValue(byte[] content, Class<T> valueType) throws IOException
1569 {
1570 return (T) forType(valueType).readValue(content);
1571 }
1572
1573 /**
1574 * Method that binds content read from given byte array,
1575 * using configuration of this reader.
1576 * Value return is either newly constructed, or root value that
1577 * was specified with {@link #withValueToUpdate(Object)}.
1578 *
1579 * @param buffer Byte array that contains encoded content to read
1580 * @param offset Offset of the first content byte in {@code buffer}
1581 * @param length Length of content in {@code buffer}, in bytes
1582 */
1583 @SuppressWarnings("unchecked")
1584 public <T> T readValue(byte[] buffer, int offset, int length) throws IOException
1585 {
1586 if (_dataFormatReaders != null) {
1587 return (T) _detectBindAndClose(buffer, offset, length);
1588 }
1589 return (T) _bindAndClose(_considerFilter(createParser(buffer, offset, length),
1590 false));
1591 }
1592
1593 /**
1594 * Same as {@link #readValue(byte[],int,int)} except that target value type
1595 * overridden as {@code valueType}
1596 *
1597 * @param buffer Byte array that contains encoded content to read
1598 * @param offset Offset of the first content byte in {@code buffer}
1599 * @param length Length of content in {@code buffer}, in bytes
1600 * @param valueType Target type to bind content to
1601 *
1602 * @since 2.11
1603 */
1604 @SuppressWarnings("unchecked")
1605 public <T> T readValue(byte[] buffer, int offset, int length, Class<T> valueType) throws IOException
1606 {
1607 return (T) forType(valueType).readValue(buffer, offset, length);
1608 }
1609
1610 /**
1611 * Method that binds content read from given {@link File}
1612 * using configuration of this reader.
1613 * Value return is either newly constructed, or root value that
1614 * was specified with {@link #withValueToUpdate(Object)}.
1615 *
1616 * @param src File that contains content to read
1617 */
1618 @SuppressWarnings("unchecked")
1619 public <T> T readValue(File src) throws IOException
1620 {
1621 if (_dataFormatReaders != null) {
1622 return (T) _detectBindAndClose(_dataFormatReaders.findFormat(_inputStream(src)), true);
1623 }
1624
1625 return (T) _bindAndClose(_considerFilter(createParser(src), false));
1626 }
1627
1628 /**
1629 * Same as {@link #readValue(File)} except that target value type
1630 * overridden as {@code valueType}
1631 *
1632 * @param src File that contains content to read
1633 * @param valueType Target type to bind content to
1634 *
1635 * @since 2.11
1636 */
1637 @SuppressWarnings("unchecked")
1638 public <T> T readValue(File src, Class<T> valueType) throws IOException
1639 {
1640 return (T) forType(valueType).readValue(src);
1641 }
1642
1643 /**
1644 * Method that binds content read from given input source,
1645 * using configuration of this reader.
1646 * Value return is either newly constructed, or root value that
1647 * was specified with {@link #withValueToUpdate(Object)}.
1648 *<p>
1649 *<p>
1650 * NOTE: handling of {@link java.net.URL} is delegated to
1651 * {@link JsonFactory#createParser(java.net.URL)} and usually simply
1652 * calls {@link java.net.URL#openStream()}, meaning no special handling
1653 * is done. If different HTTP connection options are needed you will need
1654 * to create {@link java.io.InputStream} separately.
1655 */
1656 @SuppressWarnings("unchecked")
1657 public <T> T readValue(URL src) throws IOException
1658 {
1659 if (_dataFormatReaders != null) {
1660 return (T) _detectBindAndClose(_dataFormatReaders.findFormat(_inputStream(src)), true);
1661 }
1662 return (T) _bindAndClose(_considerFilter(createParser(src), false));
1663 }
1664
1665 /**
1666 * Same as {@link #readValue(URL)} except that target value type
1667 * overridden as {@code valueType}
1668 *
1669 * @param src URL pointing to resource that contains content to read
1670 * @param valueType Target type to bind content to
1671 *
1672 * @since 2.11
1673 */
1674 @SuppressWarnings("unchecked")
1675 public <T> T readValue(URL src, Class<T> valueType) throws IOException
1676 {
1677 return (T) forType(valueType).readValue(src);
1678 }
1679
1680 /**
1681 * Convenience method for converting results from given JSON tree into given
1682 * value type. Basically short-cut for:
1683 *<pre>
1684 * objectReader.readValue(src.traverse())
1685 *</pre>
1686 *
1687 * @param content Tree that contains content to convert
1688 */
1689 @SuppressWarnings({ "unchecked" })
1690 public <T> T readValue(JsonNode content) throws IOException
1691 {
1692 _assertNotNull("content", content);
1693 if (_dataFormatReaders != null) {
1694 _reportUndetectableSource(content);
1695 }
1696 return (T) _bindAndClose(_considerFilter(treeAsTokens(content), false));
1697 }
1698
1699 /**
1700 * Same as {@link #readValue(JsonNode)} except that target value type
1701 * overridden as {@code valueType}
1702 *
1703 * @param content Tree that contains content to convert
1704 * @param valueType Target type to convert content to
1705 *
1706 * @since 2.11
1707 */
1708 @SuppressWarnings({ "unchecked" })
1709 public <T> T readValue(JsonNode content, Class<T> valueType) throws IOException
1710 {
1711 return (T) forType(valueType).readValue(content);
1712 }
1713
1714 @SuppressWarnings("unchecked")
1715 public <T> T readValue(DataInput src) throws IOException
1716 {
1717 if (_dataFormatReaders != null) {
1718 _reportUndetectableSource(src);
1719 }
1720 return (T) _bindAndClose(_considerFilter(createParser(src), false));
1721 }
1722
1723 /**
1724 * Same as {@link #readValue(DataInput)} except that target value type
1725 * overridden as {@code valueType}
1726 *
1727 * @param content DataInput that contains content to read
1728 * @param valueType Target type to bind content to
1729 *
1730 * @since 2.11
1731 */
1732 @SuppressWarnings("unchecked")
1733 public <T> T readValue(DataInput content, Class<T> valueType) throws IOException
1734 {
1735 return (T) forType(valueType).readValue(content);
1736 }
1737
1738 /*
1739 /**********************************************************
1740 /* Deserialization methods; JsonNode ("tree")
1741 /**********************************************************
1742 */
1743
1744 /**
1745 * Method that reads content from given input source,
1746 * using configuration of this reader, and binds it as JSON Tree.
1747 * Returns {@link JsonNode} that represents the root of the resulting tree, if there
1748 * was content to read, or "missing node" (instance of {@link JsonNode} for which
1749 * {@link JsonNode#isMissingNode()} returns true, and behaves otherwise similar to
1750 * "null node") if no more content is accessible through passed-in input source.
1751 *<p>
1752 * NOTE! Behavior with end-of-input (no more content) differs between this
1753 * {@code readTree} method, and {@link #readTree(JsonParser)} -- latter returns
1754 * {@code null} for "no content" case.
1755 *<p>
1756 * Note that if an object was specified with a call to
1757 * {@link #withValueToUpdate(Object)}
1758 * it will just be ignored; result is always a newly constructed
1759 * {@link JsonNode} instance.
1760 */
1761 public JsonNode readTree(InputStream src) throws IOException
1762 {
1763 if (_dataFormatReaders != null) {
1764 return _detectBindAndCloseAsTree(src);
1765 }
1766 return _bindAndCloseAsTree(_considerFilter(createParser(src), false));
1767 }
1768
1769 /**
1770 * Same as {@link #readTree(InputStream)} except content accessed through
1771 * passed-in {@link Reader}
1772 */
1773 public JsonNode readTree(Reader src) throws IOException
1774 {
1775 if (_dataFormatReaders != null) {
1776 _reportUndetectableSource(src);
1777 }
1778 return _bindAndCloseAsTree(_considerFilter(createParser(src), false));
1779 }
1780
1781 /**
1782 * Same as {@link #readTree(InputStream)} except content read from
1783 * passed-in {@link String}
1784 */
1785 public JsonNode readTree(String json) throws JsonProcessingException, JsonMappingException
1786 {
1787 if (_dataFormatReaders != null) {
1788 _reportUndetectableSource(json);
1789 }
1790 try { // since 2.10 remove "impossible" IOException as per [databind#1675]
1791 return _bindAndCloseAsTree(_considerFilter(createParser(json), false));
1792 } catch (JsonProcessingException e) {
1793 throw e;
1794 } catch (IOException e) { // shouldn't really happen but being declared need to
1795 throw JsonMappingException.fromUnexpectedIOE(e);
1796 }
1797 }
1798
1799 /**
1800 * Same as {@link #readTree(InputStream)} except content read from
1801 * passed-in byte array.
1802 */
1803 public JsonNode readTree(byte[] json) throws IOException
1804 {
1805 _assertNotNull("json", json);
1806 if (_dataFormatReaders != null) {
1807 _reportUndetectableSource(json);
1808 }
1809 return _bindAndCloseAsTree(_considerFilter(createParser(json), false));
1810 }
1811
1812 /**
1813 * Same as {@link #readTree(InputStream)} except content read from
1814 * passed-in byte array.
1815 */
1816 public JsonNode readTree(byte[] json, int offset, int len) throws IOException
1817 {
1818 if (_dataFormatReaders != null) {
1819 _reportUndetectableSource(json);
1820 }
1821 return _bindAndCloseAsTree(_considerFilter(createParser(json, offset, len), false));
1822 }
1823
1824 /**
1825 * Same as {@link #readTree(InputStream)} except content read using
1826 * passed-in {@link DataInput}.
1827 */
1828 public JsonNode readTree(DataInput src) throws IOException
1829 {
1830 if (_dataFormatReaders != null) {
1831 _reportUndetectableSource(src);
1832 }
1833 return _bindAndCloseAsTree(_considerFilter(createParser(src), false));
1834 }
1835
1836 /*
1837 /**********************************************************
1838 /* Deserialization methods; reading sequence of values
1839 /**********************************************************
1840 */
1841
1842 /**
1843 * Method for reading sequence of Objects from parser stream.
1844 *<p>
1845 * Sequence can be either root-level "unwrapped" sequence (without surrounding
1846 * JSON array), or a sequence contained in a JSON Array.
1847 * In either case {@link JsonParser} must point to the first token of
1848 * the first element, OR not point to any token (in which case it is advanced
1849 * to the next token). This means, specifically, that for wrapped sequences,
1850 * parser MUST NOT point to the surrounding <code>START_ARRAY</code> but rather
1851 * to the token following it.
1852 */
1853 public <T> MappingIterator<T> readValues(JsonParser p) throws IOException
1854 {
1855 _assertNotNull("p", p);
1856 DeserializationContext ctxt = createDeserializationContext(p);
1857 // false -> do not close as caller gave parser instance
1858 return _newIterator(p, ctxt, _findRootDeserializer(ctxt), false);
1859 }
1860
1861 /**
1862 * Method for reading sequence of Objects from parser stream.
1863 *<p>
1864 * Sequence can be either wrapped or unwrapped root-level sequence:
1865 * wrapped means that the elements are enclosed in JSON Array;
1866 * and unwrapped that elements are directly accessed at main level.
1867 * Assumption is that iff the first token of the document is
1868 * <code>START_ARRAY</code>, we have a wrapped sequence; otherwise
1869 * unwrapped. For wrapped sequences, leading <code>START_ARRAY</code>
1870 * is skipped, so that for both cases, underlying {@link JsonParser}
1871 * will point to what is expected to be the first token of the first
1872 * element.
1873 *<p>
1874 * Note that the wrapped vs unwrapped logic means that it is NOT
1875 * possible to use this method for reading an unwrapped sequence
1876 * of elements written as JSON Arrays: to read such sequences, one
1877 * has to use {@link #readValues(JsonParser)}, making sure parser
1878 * points to the first token of the first element (i.e. the second
1879 * <code>START_ARRAY</code> which is part of the first element).
1880 */
1881 public <T> MappingIterator<T> readValues(InputStream src) throws IOException
1882 {
1883 if (_dataFormatReaders != null) {
1884 return _detectBindAndReadValues(_dataFormatReaders.findFormat(src), false);
1885 }
1886
1887 return _bindAndReadValues(_considerFilter(createParser(src), true));
1888 }
1889
1890 /**
1891 * Overloaded version of {@link #readValue(InputStream)}.
1892 */
1893 @SuppressWarnings("resource")
1894 public <T> MappingIterator<T> readValues(Reader src) throws IOException
1895 {
1896 if (_dataFormatReaders != null) {
1897 _reportUndetectableSource(src);
1898 }
1899 JsonParser p = _considerFilter(createParser(src), true);
1900 DeserializationContext ctxt = createDeserializationContext(p);
1901 _initForMultiRead(ctxt, p);
1902 p.nextToken();
1903 return _newIterator(p, ctxt, _findRootDeserializer(ctxt), true);
1904 }
1905
1906 /**
1907 * Overloaded version of {@link #readValue(InputStream)}.
1908 *
1909 * @param json String that contains JSON content to parse
1910 */
1911 @SuppressWarnings("resource")
1912 public <T> MappingIterator<T> readValues(String json) throws IOException
1913 {
1914 if (_dataFormatReaders != null) {
1915 _reportUndetectableSource(json);
1916 }
1917 JsonParser p = _considerFilter(createParser(json), true);
1918 DeserializationContext ctxt = createDeserializationContext(p);
1919 _initForMultiRead(ctxt, p);
1920 p.nextToken();
1921 return _newIterator(p, ctxt, _findRootDeserializer(ctxt), true);
1922 }
1923
1924 /**
1925 * Overloaded version of {@link #readValue(InputStream)}.
1926 */
1927 public <T> MappingIterator<T> readValues(byte[] src, int offset, int length) throws IOException
1928 {
1929 if (_dataFormatReaders != null) {
1930 return _detectBindAndReadValues(_dataFormatReaders.findFormat(src, offset, length), false);
1931 }
1932 return _bindAndReadValues(_considerFilter(createParser(src, offset, length),
1933 true));
1934 }
1935
1936 /**
1937 * Overloaded version of {@link #readValue(InputStream)}.
1938 */
1939 public final <T> MappingIterator<T> readValues(byte[] src) throws IOException {
1940 _assertNotNull("src", src);
1941 return readValues(src, 0, src.length);
1942 }
1943
1944 /**
1945 * Overloaded version of {@link #readValue(InputStream)}.
1946 */
1947 public <T> MappingIterator<T> readValues(File src) throws IOException
1948 {
1949 if (_dataFormatReaders != null) {
1950 return _detectBindAndReadValues(
1951 _dataFormatReaders.findFormat(_inputStream(src)), false);
1952 }
1953 return _bindAndReadValues(_considerFilter(createParser(src), true));
1954 }
1955
1956 /**
1957 * Overloaded version of {@link #readValue(InputStream)}.
1958 *<p>
1959 * NOTE: handling of {@link java.net.URL} is delegated to
1960 * {@link JsonFactory#createParser(java.net.URL)} and usually simply
1961 * calls {@link java.net.URL#openStream()}, meaning no special handling
1962 * is done. If different HTTP connection options are needed you will need
1963 * to create {@link java.io.InputStream} separately.
1964 *
1965 * @param src URL to read to access JSON content to parse.
1966 */
1967 public <T> MappingIterator<T> readValues(URL src) throws IOException
1968 {
1969 if (_dataFormatReaders != null) {
1970 return _detectBindAndReadValues(
1971 _dataFormatReaders.findFormat(_inputStream(src)), true);
1972 }
1973 return _bindAndReadValues(_considerFilter(createParser(src), true));
1974 }
1975
1976 /**
1977 * @since 2.8
1978 */
1979 public <T> MappingIterator<T> readValues(DataInput src) throws IOException
1980 {
1981 if (_dataFormatReaders != null) {
1982 _reportUndetectableSource(src);
1983 }
1984 return _bindAndReadValues(_considerFilter(createParser(src), true));
1985 }
1986
1987 /*
1988 /**********************************************************
1989 /* Implementation of rest of ObjectCodec methods
1990 /**********************************************************
1991 */
1992
1993 @Override
1994 public <T> T treeToValue(TreeNode n, Class<T> valueType) throws JsonProcessingException
1995 {
1996 _assertNotNull("n", n);
1997 try {
1998 return readValue(treeAsTokens(n), valueType);
1999 } catch (JsonProcessingException e) {
2000 throw e;
2001 } catch (IOException e) { // should not occur, no real i/o...
2002 throw JsonMappingException.fromUnexpectedIOE(e);
2003 }
2004 }
2005
2006 @Override
2007 public void writeValue(JsonGenerator gen, Object value) throws IOException {
2008 throw new UnsupportedOperationException("Not implemented for ObjectReader");
2009 }
2010
2011 /*
2012 /**********************************************************
2013 /* Helper methods, data-binding
2014 /**********************************************************
2015 */
2016
2017 /**
2018 * Actual implementation of value reading+binding operation.
2019 */
2020 protected Object _bind(JsonParser p, Object valueToUpdate) throws IOException
2021 {
2022 /* First: may need to read the next token, to initialize state (either
2023 * before first read from parser, or after previous token has been cleared)
2024 */
2025 Object result;
2026 final DeserializationContext ctxt = createDeserializationContext(p);
2027 JsonToken t = _initForReading(ctxt, p);
2028 if (t == JsonToken.VALUE_NULL) {
2029 if (valueToUpdate == null) {
2030 result = _findRootDeserializer(ctxt).getNullValue(ctxt);
2031 } else {
2032 result = valueToUpdate;
2033 }
2034 } else if (t == JsonToken.END_ARRAY || t == JsonToken.END_OBJECT) {
2035 result = valueToUpdate;
2036 } else { // pointing to event other than null
2037 JsonDeserializer<Object> deser = _findRootDeserializer(ctxt);
2038 if (_unwrapRoot) {
2039 result = _unwrapAndDeserialize(p, ctxt, _valueType, deser);
2040 } else {
2041 if (valueToUpdate == null) {
2042 result = deser.deserialize(p, ctxt);
2043 } else {
2044 // 20-Mar-2017, tatu: Important! May be different from `valueToUpdate`
2045 // for immutable Objects like Java arrays; logical result
2046 result = deser.deserialize(p, ctxt, valueToUpdate);
2047 }
2048 }
2049 }
2050 // Need to consume the token too
2051 p.clearCurrentToken();
2052 if (_config.isEnabled(DeserializationFeature.FAIL_ON_TRAILING_TOKENS)) {
2053 _verifyNoTrailingTokens(p, ctxt, _valueType);
2054 }
2055 return result;
2056 }
2057
2058 protected Object _bindAndClose(JsonParser p0) throws IOException
2059 {
2060 try (JsonParser p = p0) {
2061 Object result;
2062
2063 DeserializationContext ctxt = createDeserializationContext(p);
2064 JsonToken t = _initForReading(ctxt, p);
2065 if (t == JsonToken.VALUE_NULL) {
2066 if (_valueToUpdate == null) {
2067 result = _findRootDeserializer(ctxt).getNullValue(ctxt);
2068 } else {
2069 result = _valueToUpdate;
2070 }
2071 } else if (t == JsonToken.END_ARRAY || t == JsonToken.END_OBJECT) {
2072 result = _valueToUpdate;
2073 } else {
2074 JsonDeserializer<Object> deser = _findRootDeserializer(ctxt);
2075 if (_unwrapRoot) {
2076 result = _unwrapAndDeserialize(p, ctxt, _valueType, deser);
2077 } else {
2078 if (_valueToUpdate == null) {
2079 result = deser.deserialize(p, ctxt);
2080 } else {
2081 deser.deserialize(p, ctxt, _valueToUpdate);
2082 result = _valueToUpdate;
2083 }
2084 }
2085 }
2086 if (_config.isEnabled(DeserializationFeature.FAIL_ON_TRAILING_TOKENS)) {
2087 _verifyNoTrailingTokens(p, ctxt, _valueType);
2088 }
2089 return result;
2090 }
2091 }
2092
2093 protected final JsonNode _bindAndCloseAsTree(JsonParser p0) throws IOException {
2094 try (JsonParser p = p0) {
2095 return _bindAsTree(p);
2096 }
2097 }
2098
2099 protected final JsonNode _bindAsTree(JsonParser p) throws IOException
2100 {
2101 // Need to inline `_initForReading()` due to tree reading handling end-of-input specially
2102 _config.initialize(p);
2103 if (_schema != null) {
2104 p.setSchema(_schema);
2105 }
2106
2107 JsonToken t = p.getCurrentToken();
2108 if (t == null) {
2109 t = p.nextToken();
2110 if (t == null) {
2111 return _config.getNodeFactory().missingNode();
2112 }
2113 }
2114 final DeserializationContext ctxt;
2115 final JsonNode resultNode;
2116 final boolean checkTrailing = _config.isEnabled(DeserializationFeature.FAIL_ON_TRAILING_TOKENS);
2117
2118 if (t == JsonToken.VALUE_NULL) {
2119 resultNode = _config.getNodeFactory().nullNode();
2120 if (!checkTrailing) {
2121 return resultNode;
2122 }
2123 ctxt = createDeserializationContext(p);
2124 } else {
2125 ctxt = createDeserializationContext(p);
2126 final JsonDeserializer<Object> deser = _findTreeDeserializer(ctxt);
2127 if (_unwrapRoot) {
2128 resultNode = (JsonNode) _unwrapAndDeserialize(p, ctxt, _jsonNodeType(), deser);
2129 } else {
2130 resultNode = (JsonNode) deser.deserialize(p, ctxt);
2131 }
2132 }
2133 if (_config.isEnabled(DeserializationFeature.FAIL_ON_TRAILING_TOKENS)) {
2134 _verifyNoTrailingTokens(p, ctxt, _jsonNodeType());
2135 }
2136 return resultNode;
2137 }
2138
2139 /**
2140 * Same as {@link #_bindAsTree} except end-of-input is reported by returning
2141 * {@code null}, not "missing node"
2142 */
2143 protected final JsonNode _bindAsTreeOrNull(JsonParser p) throws IOException
2144 {
2145 _config.initialize(p);
2146 if (_schema != null) {
2147 p.setSchema(_schema);
2148 }
2149 JsonToken t = p.getCurrentToken();
2150 if (t == null) {
2151 t = p.nextToken();
2152 if (t == null) {
2153 return null;
2154 }
2155 }
2156 final DeserializationContext ctxt;
2157 final JsonNode resultNode;
2158 final boolean checkTrailing = _config.isEnabled(DeserializationFeature.FAIL_ON_TRAILING_TOKENS);
2159 if (t == JsonToken.VALUE_NULL) {
2160 resultNode = _config.getNodeFactory().nullNode();
2161 if (!checkTrailing) {
2162 return resultNode;
2163 }
2164 ctxt = createDeserializationContext(p);
2165 } else {
2166 ctxt = createDeserializationContext(p);
2167 final JsonDeserializer<Object> deser = _findTreeDeserializer(ctxt);
2168 if (_unwrapRoot) {
2169 resultNode = (JsonNode) _unwrapAndDeserialize(p, ctxt, _jsonNodeType(), deser);
2170 } else {
2171 resultNode = (JsonNode) deser.deserialize(p, ctxt);
2172 }
2173 }
2174 if (checkTrailing) {
2175 _verifyNoTrailingTokens(p, ctxt, _jsonNodeType());
2176 }
2177 return resultNode;
2178 }
2179
2180 /**
2181 * @since 2.1
2182 */
2183 protected <T> MappingIterator<T> _bindAndReadValues(JsonParser p) throws IOException
2184 {
2185 DeserializationContext ctxt = createDeserializationContext(p);
2186 _initForMultiRead(ctxt, p);
2187 p.nextToken();
2188 return _newIterator(p, ctxt, _findRootDeserializer(ctxt), true);
2189 }
2190
2191 protected Object _unwrapAndDeserialize(JsonParser p, DeserializationContext ctxt,
2192 JavaType rootType, JsonDeserializer<Object> deser) throws IOException
2193 {
2194 PropertyName expRootName = _config.findRootName(rootType);
2195 // 12-Jun-2015, tatu: Should try to support namespaces etc but...
2196 String expSimpleName = expRootName.getSimpleName();
2197
2198 if (p.getCurrentToken() != JsonToken.START_OBJECT) {
2199 ctxt.reportWrongTokenException(rootType, JsonToken.START_OBJECT,
2200 "Current token not START_OBJECT (needed to unwrap root name '%s'), but %s",
2201 expSimpleName, p.getCurrentToken());
2202 }
2203 if (p.nextToken() != JsonToken.FIELD_NAME) {
2204 ctxt.reportWrongTokenException(rootType, JsonToken.FIELD_NAME,
2205 "Current token not FIELD_NAME (to contain expected root name '%s'), but %s",
2206 expSimpleName, p.getCurrentToken());
2207 }
2208 String actualName = p.getCurrentName();
2209 if (!expSimpleName.equals(actualName)) {
2210 ctxt.reportPropertyInputMismatch(rootType, actualName,
2211 "Root name '%s' does not match expected ('%s') for type %s",
2212 actualName, expSimpleName, rootType);
2213 }
2214 // ok, then move to value itself....
2215 p.nextToken();
2216 Object result;
2217 if (_valueToUpdate == null) {
2218 result = deser.deserialize(p, ctxt);
2219 } else {
2220 deser.deserialize(p, ctxt, _valueToUpdate);
2221 result = _valueToUpdate;
2222 }
2223 // and last, verify that we now get matching END_OBJECT
2224 if (p.nextToken() != JsonToken.END_OBJECT) {
2225 ctxt.reportWrongTokenException(rootType, JsonToken.END_OBJECT,
2226 "Current token not END_OBJECT (to match wrapper object with root name '%s'), but %s",
2227 expSimpleName, p.getCurrentToken());
2228 }
2229 if (_config.isEnabled(DeserializationFeature.FAIL_ON_TRAILING_TOKENS)) {
2230 _verifyNoTrailingTokens(p, ctxt, _valueType);
2231 }
2232 return result;
2233 }
2234
2235 /**
2236 * Consider filter when creating JsonParser.
2237 */
2238 protected JsonParser _considerFilter(final JsonParser p, boolean multiValue) {
2239 // 26-Mar-2016, tatu: Need to allow multiple-matches at least if we have
2240 // have a multiple-value read (that is, "readValues()").
2241 return ((_filter == null) || FilteringParserDelegate.class.isInstance(p))
2242 ? p : new FilteringParserDelegate(p, _filter, false, multiValue);
2243 }
2244
2245 /**
2246 * @since 2.9
2247 */
2248 protected final void _verifyNoTrailingTokens(JsonParser p, DeserializationContext ctxt,
2249 JavaType bindType)
2250 throws IOException
2251 {
2252 JsonToken t = p.nextToken();
2253 if (t != null) {
2254 Class<?> bt = ClassUtil.rawClass(bindType);
2255 if (bt == null) {
2256 if (_valueToUpdate != null) {
2257 bt = _valueToUpdate.getClass();
2258 }
2259 }
2260 ctxt.reportTrailingTokens(bt, p, t);
2261 }
2262 }
2263
2264 /*
2265 /**********************************************************
2266 /* Internal methods, format auto-detection
2267 /**********************************************************
2268 */
2269
2270 @SuppressWarnings("resource")
2271 protected Object _detectBindAndClose(byte[] src, int offset, int length) throws IOException
2272 {
2273 DataFormatReaders.Match match = _dataFormatReaders.findFormat(src, offset, length);
2274 if (!match.hasMatch()) {
2275 _reportUnkownFormat(_dataFormatReaders, match);
2276 }
2277 JsonParser p = match.createParserWithMatch();
2278 return match.getReader()._bindAndClose(p);
2279 }
2280
2281 @SuppressWarnings({ "resource" })
2282 protected Object _detectBindAndClose(DataFormatReaders.Match match, boolean forceClosing)
2283 throws IOException
2284 {
2285 if (!match.hasMatch()) {
2286 _reportUnkownFormat(_dataFormatReaders, match);
2287 }
2288 JsonParser p = match.createParserWithMatch();
2289 // One more thing: we Own the input stream now; and while it's
2290 // not super clean way to do it, we must ensure closure so:
2291 if (forceClosing) {
2292 p.enable(JsonParser.Feature.AUTO_CLOSE_SOURCE);
2293 }
2294 // important: use matching ObjectReader (may not be 'this')
2295 return match.getReader()._bindAndClose(p);
2296 }
2297
2298 @SuppressWarnings({ "resource" })
2299 protected <T> MappingIterator<T> _detectBindAndReadValues(DataFormatReaders.Match match, boolean forceClosing)
2300 throws IOException
2301 {
2302 if (!match.hasMatch()) {
2303 _reportUnkownFormat(_dataFormatReaders, match);
2304 }
2305 JsonParser p = match.createParserWithMatch();
2306 // One more thing: we Own the input stream now; and while it's
2307 // not super clean way to do it, we must ensure closure so:
2308 if (forceClosing) {
2309 p.enable(JsonParser.Feature.AUTO_CLOSE_SOURCE);
2310 }
2311 // important: use matching ObjectReader (may not be 'this')
2312 return match.getReader()._bindAndReadValues(p);
2313 }
2314
2315 @SuppressWarnings({ "resource" })
2316 protected JsonNode _detectBindAndCloseAsTree(InputStream in) throws IOException
2317 {
2318 DataFormatReaders.Match match = _dataFormatReaders.findFormat(in);
2319 if (!match.hasMatch()) {
2320 _reportUnkownFormat(_dataFormatReaders, match);
2321 }
2322 JsonParser p = match.createParserWithMatch();
2323 p.enable(JsonParser.Feature.AUTO_CLOSE_SOURCE);
2324 return match.getReader()._bindAndCloseAsTree(p);
2325 }
2326
2327 /**
2328 * Method called to indicate that format detection failed to detect format
2329 * of given input
2330 */
2331 protected void _reportUnkownFormat(DataFormatReaders detector, DataFormatReaders.Match match)
2332 throws JsonProcessingException
2333 {
2334 // 17-Aug-2015, tatu: Unfortunately, no parser/generator available so:
2335 throw new JsonParseException(null, "Cannot detect format from input, does not look like any of detectable formats "
2336 +detector.toString());
2337 }
2338
2339 /*
2340 /**********************************************************
2341 /* Internal methods, other
2342 /**********************************************************
2343 */
2344
2345 /**
2346 * @since 2.2
2347 */
2348 protected void _verifySchemaType(FormatSchema schema)
2349 {
2350 if (schema != null) {
2351 if (!_parserFactory.canUseSchema(schema)) {
2352 throw new IllegalArgumentException("Cannot use FormatSchema of type "+schema.getClass().getName()
2353 +" for format "+_parserFactory.getFormatName());
2354 }
2355 }
2356 }
2357
2358 /**
2359 * Internal helper method called to create an instance of {@link DeserializationContext}
2360 * for deserializing a single root value.
2361 * Can be overridden if a custom context is needed.
2362 */
2363 protected DefaultDeserializationContext createDeserializationContext(JsonParser p) {
2364 return _context.createInstance(_config, p, _injectableValues);
2365 }
2366
2367 protected InputStream _inputStream(URL src) throws IOException {
2368 return src.openStream();
2369 }
2370
2371 protected InputStream _inputStream(File f) throws IOException {
2372 return new FileInputStream(f);
2373 }
2374
2375 protected void _reportUndetectableSource(Object src) throws JsonParseException
2376 {
2377 // 17-Aug-2015, tatu: Unfortunately, no parser/generator available so:
2378 throw new JsonParseException(null, "Cannot use source of type "
2379 +src.getClass().getName()+" with format auto-detection: must be byte- not char-based");
2380 }
2381
2382 /*
2383 /**********************************************************
2384 /* Helper methods, locating deserializers etc
2385 /**********************************************************
2386 */
2387
2388 /**
2389 * Method called to locate deserializer for the passed root-level value.
2390 */
2391 protected JsonDeserializer<Object> _findRootDeserializer(DeserializationContext ctxt)
2392 throws JsonMappingException
2393 {
2394 if (_rootDeserializer != null) {
2395 return _rootDeserializer;
2396 }
2397
2398 // Sanity check: must have actual type...
2399 JavaType t = _valueType;
2400 if (t == null) {
2401 ctxt.reportBadDefinition((JavaType) null,
2402 "No value type configured for ObjectReader");
2403 }
2404 // First: have we already seen it?
2405 JsonDeserializer<Object> deser = _rootDeserializers.get(t);
2406 if (deser != null) {
2407 return deser;
2408 }
2409 // Nope: need to ask provider to resolve it
2410 deser = ctxt.findRootValueDeserializer(t);
2411 if (deser == null) { // can this happen?
2412 ctxt.reportBadDefinition(t, "Cannot find a deserializer for type "+t);
2413 }
2414 _rootDeserializers.put(t, deser);
2415 return deser;
2416 }
2417
2418 /**
2419 * @since 2.6
2420 */
2421 protected JsonDeserializer<Object> _findTreeDeserializer(DeserializationContext ctxt)
2422 throws JsonMappingException
2423 {
2424 final JavaType nodeType = _jsonNodeType();
2425 JsonDeserializer<Object> deser = _rootDeserializers.get(nodeType);
2426 if (deser == null) {
2427 // Nope: need to ask provider to resolve it
2428 deser = ctxt.findRootValueDeserializer(nodeType);
2429 if (deser == null) { // can this happen?
2430 ctxt.reportBadDefinition(nodeType,
2431 "Cannot find a deserializer for type "+nodeType);
2432 }
2433 _rootDeserializers.put(nodeType, deser);
2434 }
2435 return deser;
2436 }
2437
2438 /**
2439 * Method called to locate deserializer ahead of time, if permitted
2440 * by configuration. Method also is NOT to throw an exception if
2441 * access fails.
2442 */
2443 protected JsonDeserializer<Object> _prefetchRootDeserializer(JavaType valueType)
2444 {
2445 if ((valueType == null) || !_config.isEnabled(DeserializationFeature.EAGER_DESERIALIZER_FETCH)) {
2446 return null;
2447 }
2448 // already cached?
2449 JsonDeserializer<Object> deser = _rootDeserializers.get(valueType);
2450 if (deser == null) {
2451 try {
2452 // If not, need to resolve; for which we need a temporary context as well:
2453 DeserializationContext ctxt = createDeserializationContext(null);
2454 deser = ctxt.findRootValueDeserializer(valueType);
2455 if (deser != null) {
2456 _rootDeserializers.put(valueType, deser);
2457 }
2458 return deser;
2459 } catch (JsonProcessingException e) {
2460 // need to swallow?
2461 }
2462 }
2463 return deser;
2464 }
2465
2466 /**
2467 * @since 2.10
2468 */
2469 protected final JavaType _jsonNodeType() {
2470 JavaType t = _jsonNodeType;
2471 if (t == null) {
2472 t = getTypeFactory().constructType(JsonNode.class);
2473 _jsonNodeType = t;
2474 }
2475 return t;
2476 }
2477
2478 protected final void _assertNotNull(String paramName, Object src) {
2479 if (src == null) {
2480 throw new IllegalArgumentException(String.format("argument \"%s\" is null", paramName));
2481 }
2482 }
2483 }
2484