1 /* Jackson JSON-processor.
2 *
3 * Copyright (c) 2007- Tatu Saloranta, tatu.saloranta@iki.fi
4 */
5
6 package com.fasterxml.jackson.core;
7
8 import java.io.*;
9 import java.math.BigDecimal;
10 import java.math.BigInteger;
11 import java.util.Iterator;
12
13 import com.fasterxml.jackson.core.async.NonBlockingInputFeeder;
14 import com.fasterxml.jackson.core.exc.InputCoercionException;
15 import com.fasterxml.jackson.core.type.TypeReference;
16 import com.fasterxml.jackson.core.util.RequestPayload;
17
18 /**
19 * Base class that defines public API for reading JSON content.
20 * Instances are created using factory methods of
21 * a {@link JsonFactory} instance.
22 *
23 * @author Tatu Saloranta
24 */
25 public abstract class JsonParser
26 implements Closeable, Versioned
27 {
28 private final static int MIN_BYTE_I = (int) Byte.MIN_VALUE;
29 // as per [JACKSON-804], allow range up to and including 255
30 private final static int MAX_BYTE_I = (int) 255;
31
32 private final static int MIN_SHORT_I = (int) Short.MIN_VALUE;
33 private final static int MAX_SHORT_I = (int) Short.MAX_VALUE;
34
35 /**
36 * Enumeration of possible "native" (optimal) types that can be
37 * used for numbers.
38 */
39 public enum NumberType {
40 INT, LONG, BIG_INTEGER, FLOAT, DOUBLE, BIG_DECIMAL
41 };
42
43 /**
44 * Enumeration that defines all on/off features for parsers.
45 */
46 public enum Feature {
47 // // // Low-level I/O handling features:
48
49 /**
50 * Feature that determines whether parser will automatically
51 * close underlying input source that is NOT owned by the
52 * parser. If disabled, calling application has to separately
53 * close the underlying {@link InputStream} and {@link Reader}
54 * instances used to create the parser. If enabled, parser
55 * will handle closing, as long as parser itself gets closed:
56 * this happens when end-of-input is encountered, or parser
57 * is closed by a call to {@link JsonParser#close}.
58 *<p>
59 * Feature is enabled by default.
60 */
61 AUTO_CLOSE_SOURCE(true),
62
63 // // // Support for non-standard data format constructs
64
65 /**
66 * Feature that determines whether parser will allow use
67 * of Java/C++ style comments (both '/'+'*' and
68 * '//' varieties) within parsed content or not.
69 *<p>
70 * Since JSON specification does not mention comments as legal
71 * construct,
72 * this is a non-standard feature; however, in the wild
73 * this is extensively used. As such, feature is
74 * <b>disabled by default</b> for parsers and must be
75 * explicitly enabled.
76 *<p>
77 * NOTE: while not technically deprecated, since 2.10 recommended to use
78 * {@link com.fasterxml.jackson.core.json.JsonReadFeature#ALLOW_JAVA_COMMENTS} instead.
79 */
80 ALLOW_COMMENTS(false),
81
82 /**
83 * Feature that determines whether parser will allow use
84 * of YAML comments, ones starting with '#' and continuing
85 * until the end of the line. This commenting style is common
86 * with scripting languages as well.
87 *<p>
88 * Since JSON specification does not mention comments as legal
89 * construct,
90 * this is a non-standard feature. As such, feature is
91 * <b>disabled by default</b> for parsers and must be
92 * explicitly enabled.
93 *<p>
94 * NOTE: while not technically deprecated, since 2.10 recommended to use
95 * {@link com.fasterxml.jackson.core.json.JsonReadFeature#ALLOW_YAML_COMMENTS} instead.
96 */
97 ALLOW_YAML_COMMENTS(false),
98
99 /**
100 * Feature that determines whether parser will allow use
101 * of unquoted field names (which is allowed by Javascript,
102 * but not by JSON specification).
103 *<p>
104 * Since JSON specification requires use of double quotes for
105 * field names,
106 * this is a non-standard feature, and as such disabled by default.
107 *<p>
108 * NOTE: while not technically deprecated, since 2.10 recommended to use
109 * {@link com.fasterxml.jackson.core.json.JsonReadFeature#ALLOW_UNQUOTED_FIELD_NAMES} instead.
110 */
111 ALLOW_UNQUOTED_FIELD_NAMES(false),
112
113 /**
114 * Feature that determines whether parser will allow use
115 * of single quotes (apostrophe, character '\'') for
116 * quoting Strings (names and String values). If so,
117 * this is in addition to other acceptable markers.
118 * but not by JSON specification).
119 *<p>
120 * Since JSON specification requires use of double quotes for
121 * field names,
122 * this is a non-standard feature, and as such disabled by default.
123 *<p>
124 * NOTE: while not technically deprecated, since 2.10 recommended to use
125 * {@link com.fasterxml.jackson.core.json.JsonReadFeature#ALLOW_SINGLE_QUOTES} instead.
126 */
127 ALLOW_SINGLE_QUOTES(false),
128
129 /**
130 * Feature that determines whether parser will allow
131 * JSON Strings to contain unquoted control characters
132 * (ASCII characters with value less than 32, including
133 * tab and line feed characters) or not.
134 * If feature is set false, an exception is thrown if such a
135 * character is encountered.
136 *<p>
137 * Since JSON specification requires quoting for all control characters,
138 * this is a non-standard feature, and as such disabled by default.
139 *
140 * @deprecated Since 2.10 use {@link com.fasterxml.jackson.core.json.JsonReadFeature#ALLOW_UNESCAPED_CONTROL_CHARS} instead
141 */
142 @Deprecated
143 ALLOW_UNQUOTED_CONTROL_CHARS(false),
144
145 /**
146 * Feature that can be enabled to accept quoting of all character
147 * using backslash quoting mechanism: if not enabled, only characters
148 * that are explicitly listed by JSON specification can be thus
149 * escaped (see JSON spec for small list of these characters)
150 *<p>
151 * Since JSON specification requires quoting for all control characters,
152 * this is a non-standard feature, and as such disabled by default.
153 *
154 * @deprecated Since 2.10 use {@link com.fasterxml.jackson.core.json.JsonReadFeature#ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER} instead
155 */
156 @Deprecated
157 ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER(false),
158
159 /**
160 * Feature that determines whether parser will allow
161 * JSON integral numbers to start with additional (ignorable)
162 * zeroes (like: 000001). If enabled, no exception is thrown, and extra
163 * nulls are silently ignored (and not included in textual representation
164 * exposed via {@link JsonParser#getText}).
165 *<p>
166 * Since JSON specification does not allow leading zeroes,
167 * this is a non-standard feature, and as such disabled by default.
168 *
169 * @deprecated Since 2.10 use {@link com.fasterxml.jackson.core.json.JsonReadFeature#ALLOW_LEADING_ZEROS_FOR_NUMBERS} instead
170 */
171 @Deprecated
172 ALLOW_NUMERIC_LEADING_ZEROS(false),
173
174 /**
175 * @deprecated Use {@link com.fasterxml.jackson.core.json.JsonReadFeature#ALLOW_LEADING_DECIMAL_POINT_FOR_NUMBERS} instead
176 */
177 @Deprecated
178 ALLOW_LEADING_DECIMAL_POINT_FOR_NUMBERS(false),
179
180 /**
181 * Feature that allows parser to recognize set of
182 * "Not-a-Number" (NaN) tokens as legal floating number
183 * values (similar to how many other data formats and
184 * programming language source code allows it).
185 * Specific subset contains values that
186 * <a href="http://www.w3.org/TR/xmlschema-2/">XML Schema</a>
187 * (see section 3.2.4.1, Lexical Representation)
188 * allows (tokens are quoted contents, not including quotes):
189 *<ul>
190 * <li>"INF" (for positive infinity), as well as alias of "Infinity"
191 * <li>"-INF" (for negative infinity), alias "-Infinity"
192 * <li>"NaN" (for other not-a-numbers, like result of division by zero)
193 *</ul>
194 *<p>
195 * Since JSON specification does not allow use of such values,
196 * this is a non-standard feature, and as such disabled by default.
197 *
198 * @deprecated Since 2.10 use {@link com.fasterxml.jackson.core.json.JsonReadFeature#ALLOW_NON_NUMERIC_NUMBERS} instead
199 */
200 @Deprecated
201 ALLOW_NON_NUMERIC_NUMBERS(false),
202
203 /**
204 * Feature allows the support for "missing" values in a JSON array: missing
205 * value meaning sequence of two commas, without value in-between but only
206 * optional white space.
207 * Enabling this feature will expose "missing" values as {@link JsonToken#VALUE_NULL}
208 * tokens, which typically become Java nulls in arrays and {@link java.util.Collection}
209 * in data-binding.
210 * <p>
211 * For example, enabling this feature will represent a JSON array <code>["value1",,"value3",]</code>
212 * as <code>["value1", null, "value3", null]</code>
213 * <p>
214 * Since the JSON specification does not allow missing values this is a non-compliant JSON
215 * feature and is disabled by default.
216 *
217 * @since 2.8
218 *
219 * @deprecated Since 2.10 use {@link com.fasterxml.jackson.core.json.JsonReadFeature#ALLOW_MISSING_VALUES} instead
220 */
221 @Deprecated
222 ALLOW_MISSING_VALUES(false),
223
224 /**
225 * Feature that determines whether {@link JsonParser} will allow for a single trailing
226 * comma following the final value (in an Array) or member (in an Object). These commas
227 * will simply be ignored.
228 * <p>
229 * For example, when this feature is enabled, <code>[true,true,]</code> is equivalent to
230 * <code>[true, true]</code> and <code>{"a": true,}</code> is equivalent to
231 * <code>{"a": true}</code>.
232 * <p>
233 * When combined with <code>ALLOW_MISSING_VALUES</code>, this feature takes priority, and
234 * the final trailing comma in an array declaration does not imply a missing
235 * (<code>null</code>) value. For example, when both <code>ALLOW_MISSING_VALUES</code>
236 * and <code>ALLOW_TRAILING_COMMA</code> are enabled, <code>[true,true,]</code> is
237 * equivalent to <code>[true, true]</code>, and <code>[true,true,,]</code> is equivalent to
238 * <code>[true, true, null]</code>.
239 * <p>
240 * Since the JSON specification does not permit trailing commas, this is a non-standard
241 * feature, and as such disabled by default.
242 *
243 * @since 2.9
244 *
245 * @deprecated Since 2.10 use {@link com.fasterxml.jackson.core.json.JsonReadFeature#ALLOW_TRAILING_COMMA} instead
246 */
247 @Deprecated
248 ALLOW_TRAILING_COMMA(false),
249
250 // // // Validity checks
251
252 /**
253 * Feature that determines whether {@link JsonParser} will explicitly
254 * check that no duplicate JSON Object field names are encountered.
255 * If enabled, parser will check all names within context and report
256 * duplicates by throwing a {@link JsonParseException}; if disabled,
257 * parser will not do such checking. Assumption in latter case is
258 * that caller takes care of handling duplicates at a higher level:
259 * data-binding, for example, has features to specify detection to
260 * be done there.
261 *<p>
262 * Note that enabling this feature will incur performance overhead
263 * due to having to store and check additional information: this typically
264 * adds 20-30% to execution time for basic parsing.
265 *
266 * @since 2.3
267 */
268 STRICT_DUPLICATE_DETECTION(false),
269
270 /**
271 * Feature that determines what to do if the underlying data format requires knowledge
272 * of all properties to decode (usually via a Schema), and if no definition is
273 * found for a property that input content contains.
274 * Typically most textual data formats do NOT require schema information (although
275 * some do, such as CSV), whereas many binary data formats do require definitions
276 * (such as Avro, protobuf), although not all (Smile, CBOR, BSON and MessagePack do not).
277 * Further note that some formats that do require schema information will not be able
278 * to ignore undefined properties: for example, Avro is fully positional and there is
279 * no possibility of undefined data. This leaves formats like Protobuf that have identifiers
280 * that may or may not map; and as such Protobuf format does make use of this feature.
281 *<p>
282 * Note that support for this feature is implemented by individual data format
283 * module, if (and only if) it makes sense for the format in question. For JSON,
284 * for example, this feature has no effect as properties need not be pre-defined.
285 *<p>
286 * Feature is disabled by default, meaning that if the underlying data format
287 * requires knowledge of all properties to output, attempts to read an unknown
288 * property will result in a {@link JsonProcessingException}
289 *
290 * @since 2.6
291 */
292 IGNORE_UNDEFINED(false),
293
294 // // // Other
295
296 /**
297 * Feature that determines whether {@link JsonLocation} instances should be constructed
298 * with reference to source or not. If source reference is included, its type and contents
299 * are included when `toString()` method is called (most notably when printing out parse
300 * exception with that location information). If feature is disabled, no source reference
301 * is passed and source is only indicated as "UNKNOWN".
302 *<p>
303 * Most common reason for disabling this feature is to avoid leaking information about
304 * internal information; this may be done for security reasons.
305 * Note that even if source reference is included, only parts of contents are usually
306 * printed, and not the whole contents. Further, many source reference types can not
307 * necessarily access contents (like streams), so only type is indicated, not contents.
308 *<p>
309 * Feature is enabled by default, meaning that "source reference" information is passed
310 * and some or all of the source content may be included in {@link JsonLocation} information
311 * constructed either when requested explicitly, or when needed for an exception.
312 *
313 * @since 2.9
314 */
315 INCLUDE_SOURCE_IN_LOCATION(true),
316
317 ;
318
319 /**
320 * Whether feature is enabled or disabled by default.
321 */
322 private final boolean _defaultState;
323
324 private final int _mask;
325
326 /**
327 * Method that calculates bit set (flags) of all features that
328 * are enabled by default.
329 */
330 public static int collectDefaults()
331 {
332 int flags = 0;
333 for (Feature f : values()) {
334 if (f.enabledByDefault()) {
335 flags |= f.getMask();
336 }
337 }
338 return flags;
339 }
340
341 private Feature(boolean defaultState) {
342 _mask = (1 << ordinal());
343 _defaultState = defaultState;
344 }
345
346 public boolean enabledByDefault() { return _defaultState; }
347
348 /**
349 * @since 2.3
350 */
351 public boolean enabledIn(int flags) { return (flags & _mask) != 0; }
352
353 public int getMask() { return _mask; }
354 }
355
356 /*
357 /**********************************************************
358 /* Minimal configuration state
359 /**********************************************************
360 */
361
362 /**
363 * Bit flag composed of bits that indicate which
364 * {@link com.fasterxml.jackson.core.JsonParser.Feature}s
365 * are enabled.
366 */
367 protected int _features;
368
369 /**
370 * Optional container that holds the request payload which will be displayed on JSON parsing error.
371 *
372 * @since 2.8
373 */
374 protected transient RequestPayload _requestPayload;
375
376 /*
377 /**********************************************************
378 /* Construction, configuration, initialization
379 /**********************************************************
380 */
381
382 protected JsonParser() { }
383 protected JsonParser(int features) { _features = features; }
384
385 /**
386 * Accessor for {@link ObjectCodec} associated with this
387 * parser, if any. Codec is used by {@link #readValueAs(Class)}
388 * method (and its variants).
389 */
390 public abstract ObjectCodec getCodec();
391
392 /**
393 * Setter that allows defining {@link ObjectCodec} associated with this
394 * parser, if any. Codec is used by {@link #readValueAs(Class)}
395 * method (and its variants).
396 */
397 public abstract void setCodec(ObjectCodec c);
398
399 /**
400 * Method that can be used to get access to object that is used
401 * to access input being parsed; this is usually either
402 * {@link InputStream} or {@link Reader}, depending on what
403 * parser was constructed with.
404 * Note that returned value may be null in some cases; including
405 * case where parser implementation does not want to exposed raw
406 * source to caller.
407 * In cases where input has been decorated, object returned here
408 * is the decorated version; this allows some level of interaction
409 * between users of parser and decorator object.
410 *<p>
411 * In general use of this accessor should be considered as
412 * "last effort", i.e. only used if no other mechanism is applicable.
413 */
414 public Object getInputSource() { return null; }
415
416 /**
417 * Helper method, usually equivalent to:
418 *<code>
419 * getParsingContext().getCurrentValue();
420 *</code>
421 *<p>
422 * Note that "current value" is NOT populated (or used) by Streaming parser;
423 * it is only used by higher-level data-binding functionality.
424 * The reason it is included here is that it can be stored and accessed hierarchically,
425 * and gets passed through data-binding.
426 *
427 * @since 2.5
428 */
429 public Object getCurrentValue() {
430 JsonStreamContext ctxt = getParsingContext();
431 return (ctxt == null) ? null : ctxt.getCurrentValue();
432 }
433
434 /**
435 * Helper method, usually equivalent to:
436 *<code>
437 * getParsingContext().setCurrentValue(v);
438 *</code>
439 *
440 * @since 2.5
441 */
442 public void setCurrentValue(Object v) {
443 JsonStreamContext ctxt = getParsingContext();
444 if (ctxt != null) {
445 ctxt.setCurrentValue(v);
446 }
447 }
448
449 /**
450 * Sets the payload to be passed if {@link JsonParseException} is thrown.
451 *
452 * @since 2.8
453 */
454 public void setRequestPayloadOnError(RequestPayload payload) {
455 _requestPayload = payload;
456 }
457
458 /**
459 * Sets the byte[] request payload and the charset
460 *
461 * @since 2.8
462 */
463 public void setRequestPayloadOnError(byte[] payload, String charset) {
464 _requestPayload = (payload == null) ? null : new RequestPayload(payload, charset);
465 }
466
467 /**
468 * Sets the String request payload
469 *
470 * @since 2.8
471 */
472 public void setRequestPayloadOnError(String payload) {
473 _requestPayload = (payload == null) ? null : new RequestPayload(payload);
474 }
475
476 /*
477 /**********************************************************
478 /* Format support
479 /**********************************************************
480 */
481
482 /**
483 * Method to call to make this parser use specified schema. Method must
484 * be called before trying to parse any content, right after parser instance
485 * has been created.
486 * Note that not all parsers support schemas; and those that do usually only
487 * accept specific types of schemas: ones defined for data format parser can read.
488 *<p>
489 * If parser does not support specified schema, {@link UnsupportedOperationException}
490 * is thrown.
491 *
492 * @param schema Schema to use
493 *
494 * @throws UnsupportedOperationException if parser does not support schema
495 */
496 public void setSchema(FormatSchema schema) {
497 throw new UnsupportedOperationException("Parser of type "+getClass().getName()+" does not support schema of type '"
498 +schema.getSchemaType()+"'");
499 }
500
501 /**
502 * Method for accessing Schema that this parser uses, if any.
503 * Default implementation returns null.
504 *
505 * @since 2.1
506 */
507 public FormatSchema getSchema() { return null; }
508
509 /**
510 * Method that can be used to verify that given schema can be used with
511 * this parser (using {@link #setSchema}).
512 *
513 * @param schema Schema to check
514 *
515 * @return True if this parser can use given schema; false if not
516 */
517 public boolean canUseSchema(FormatSchema schema) { return false; }
518
519 /*
520 /**********************************************************
521 /* Capability introspection
522 /**********************************************************
523 */
524
525 /**
526 * Method that can be called to determine if a custom
527 * {@link ObjectCodec} is needed for binding data parsed
528 * using {@link JsonParser} constructed by this factory
529 * (which typically also implies the same for serialization
530 * with {@link JsonGenerator}).
531 *
532 * @return True if custom codec is needed with parsers and
533 * generators created by this factory; false if a general
534 * {@link ObjectCodec} is enough
535 *
536 * @since 2.1
537 */
538 public boolean requiresCustomCodec() { return false;}
539
540 /**
541 * Method that can be called to determine if this parser instance
542 * uses non-blocking ("asynchronous") input access for decoding or not.
543 * Access mode is determined by earlier calls via {@link JsonFactory};
544 * it may not be changed after construction.
545 *<p>
546 * If non-blocking decoding is u (@code true}, it is possible to call
547 * {@link #getNonBlockingInputFeeder()} to obtain object to use
548 * for feeding input; otherwise (<code>false</code> returned)
549 * input is read by blocking
550 *
551 * @since 2.9
552 */
553 public boolean canParseAsync() { return false; }
554
555 /**
556 * Method that will either return a feeder instance (if parser uses
557 * non-blocking, aka asynchronous access); or <code>null</code> for
558 * parsers that use blocking I/O.
559 *
560 * @since 2.9
561 */
562 public NonBlockingInputFeeder getNonBlockingInputFeeder() {
563 return null;
564 }
565
566 /*
567 /**********************************************************
568 /* Versioned
569 /**********************************************************
570 */
571
572 /**
573 * Accessor for getting version of the core package, given a parser instance.
574 * Left for sub-classes to implement.
575 */
576 @Override
577 public abstract Version version();
578
579 /*
580 /**********************************************************
581 /* Closeable implementation
582 /**********************************************************
583 */
584
585 /**
586 * Closes the parser so that no further iteration or data access
587 * can be made; will also close the underlying input source
588 * if parser either <b>owns</b> the input source, or feature
589 * {@link Feature#AUTO_CLOSE_SOURCE} is enabled.
590 * Whether parser owns the input source depends on factory
591 * method that was used to construct instance (so check
592 * {@link com.fasterxml.jackson.core.JsonFactory} for details,
593 * but the general
594 * idea is that if caller passes in closable resource (such
595 * as {@link InputStream} or {@link Reader}) parser does NOT
596 * own the source; but if it passes a reference (such as
597 * {@link java.io.File} or {@link java.net.URL} and creates
598 * stream or reader it does own them.
599 */
600 @Override
601 public abstract void close() throws IOException;
602
603 /**
604 * Method that can be called to determine whether this parser
605 * is closed or not. If it is closed, no new tokens can be
606 * retrieved by calling {@link #nextToken} (and the underlying
607 * stream may be closed). Closing may be due to an explicit
608 * call to {@link #close} or because parser has encountered
609 * end of input.
610 */
611 public abstract boolean isClosed();
612
613 /*
614 /**********************************************************
615 /* Public API, simple location, context accessors
616 /**********************************************************
617 */
618
619 /**
620 * Method that can be used to access current parsing context reader
621 * is in. There are 3 different types: root, array and object contexts,
622 * with slightly different available information. Contexts are
623 * hierarchically nested, and can be used for example for figuring
624 * out part of the input document that correspond to specific
625 * array or object (for highlighting purposes, or error reporting).
626 * Contexts can also be used for simple xpath-like matching of
627 * input, if so desired.
628 */
629 public abstract JsonStreamContext getParsingContext();
630
631 /**
632 * Method that return the <b>starting</b> location of the current
633 * token; that is, position of the first character from input
634 * that starts the current token.
635 */
636 public abstract JsonLocation getTokenLocation();
637
638 /**
639 * Method that returns location of the last processed character;
640 * usually for error reporting purposes.
641 */
642 public abstract JsonLocation getCurrentLocation();
643
644 /*
645 /**********************************************************
646 /* Buffer handling
647 /**********************************************************
648 */
649
650 /**
651 * Method that can be called to push back any content that
652 * has been read but not consumed by the parser. This is usually
653 * done after reading all content of interest using parser.
654 * Content is released by writing it to given stream if possible;
655 * if underlying input is byte-based it can released, if not (char-based)
656 * it can not.
657 *
658 * @return -1 if the underlying content source is not byte based
659 * (that is, input can not be sent to {@link OutputStream};
660 * otherwise number of bytes released (0 if there was nothing to release)
661 *
662 * @throws IOException if write to stream threw exception
663 */
664 public int releaseBuffered(OutputStream out) throws IOException {
665 return -1;
666 }
667
668 /**
669 * Method that can be called to push back any content that
670 * has been read but not consumed by the parser.
671 * This is usually
672 * done after reading all content of interest using parser.
673 * Content is released by writing it to given writer if possible;
674 * if underlying input is char-based it can released, if not (byte-based)
675 * it can not.
676 *
677 * @return -1 if the underlying content source is not char-based
678 * (that is, input can not be sent to {@link Writer};
679 * otherwise number of chars released (0 if there was nothing to release)
680 *
681 * @throws IOException if write using Writer threw exception
682 */
683 public int releaseBuffered(Writer w) throws IOException { return -1; }
684
685 /*
686 /***************************************************
687 /* Public API, configuration
688 /***************************************************
689 */
690
691 /**
692 * Method for enabling specified parser feature
693 * (check {@link Feature} for list of features)
694 */
695 public JsonParser enable(Feature f) {
696 _features |= f.getMask();
697 return this;
698 }
699
700 /**
701 * Method for disabling specified feature
702 * (check {@link Feature} for list of features)
703 */
704 public JsonParser disable(Feature f) {
705 _features &= ~f.getMask();
706 return this;
707 }
708
709 /**
710 * Method for enabling or disabling specified feature
711 * (check {@link Feature} for list of features)
712 */
713 public JsonParser configure(Feature f, boolean state) {
714 if (state) enable(f); else disable(f);
715 return this;
716 }
717
718 /**
719 * Method for checking whether specified {@link Feature} is enabled.
720 */
721 public boolean isEnabled(Feature f) { return f.enabledIn(_features); }
722
723 /**
724 * Method for checking whether specified {@link Feature} is enabled.
725 *
726 * @since 2.10
727 */
728 public boolean isEnabled(StreamReadFeature f) { return f.mappedFeature().enabledIn(_features); }
729
730 /**
731 * Bulk access method for getting state of all standard {@link Feature}s.
732 *
733 * @return Bit mask that defines current states of all standard {@link Feature}s.
734 *
735 * @since 2.3
736 */
737 public int getFeatureMask() { return _features; }
738
739 /**
740 * Bulk set method for (re)setting states of all standard {@link Feature}s
741 *
742 * @return This parser object, to allow chaining of calls
743 *
744 * @since 2.3
745 *
746 * @deprecated Since 2.7, use {@link #overrideStdFeatures(int, int)} instead
747 */
748 @Deprecated
749 public JsonParser setFeatureMask(int mask) {
750 _features = mask;
751 return this;
752 }
753
754 /**
755 * Bulk set method for (re)setting states of features specified by <code>mask</code>.
756 * Functionally equivalent to
757 *<code>
758 * int oldState = getFeatureMask();
759 * int newState = (oldState & ~mask) | (values & mask);
760 * setFeatureMask(newState);
761 *</code>
762 * but preferred as this lets caller more efficiently specify actual changes made.
763 *
764 * @param values Bit mask of set/clear state for features to change
765 * @param mask Bit mask of features to change
766 *
767 * @since 2.6
768 */
769 public JsonParser overrideStdFeatures(int values, int mask) {
770 int newState = (_features & ~mask) | (values & mask);
771 return setFeatureMask(newState);
772 }
773
774 /**
775 * Bulk access method for getting state of all {@link FormatFeature}s, format-specific
776 * on/off configuration settings.
777 *
778 * @return Bit mask that defines current states of all standard {@link FormatFeature}s.
779 *
780 * @since 2.6
781 */
782 public int getFormatFeatures() {
783 return 0;
784 }
785
786 /**
787 * Bulk set method for (re)setting states of {@link FormatFeature}s,
788 * by specifying values (set / clear) along with a mask, to determine
789 * which features to change, if any.
790 *<p>
791 * Default implementation will simply throw an exception to indicate that
792 * the generator implementation does not support any {@link FormatFeature}s.
793 *
794 * @param values Bit mask of set/clear state for features to change
795 * @param mask Bit mask of features to change
796 *
797 * @since 2.6
798 */
799 public JsonParser overrideFormatFeatures(int values, int mask) {
800 // 08-Oct-2018, tatu: For 2.10 we actually do get `JsonReadFeature`s, although they
801 // are (for 2.x only, not for 3.x) mapper to legacy settings. So do not freak out:
802 // throw new IllegalArgumentException("No FormatFeatures defined for parser of type "+getClass().getName());
803 return this;
804 }
805
806 /*
807 /**********************************************************
808 /* Public API, traversal
809 /**********************************************************
810 */
811
812 /**
813 * Main iteration method, which will advance stream enough
814 * to determine type of the next token, if any. If none
815 * remaining (stream has no content other than possible
816 * white space before ending), null will be returned.
817 *
818 * @return Next token from the stream, if any found, or null
819 * to indicate end-of-input
820 */
821 public abstract JsonToken nextToken() throws IOException;
822
823 /**
824 * Iteration method that will advance stream enough
825 * to determine type of the next token that is a value type
826 * (including JSON Array and Object start/end markers).
827 * Or put another way, nextToken() will be called once,
828 * and if {@link JsonToken#FIELD_NAME} is returned, another
829 * time to get the value for the field.
830 * Method is most useful for iterating over value entries
831 * of JSON objects; field name will still be available
832 * by calling {@link #getCurrentName} when parser points to
833 * the value.
834 *
835 * @return Next non-field-name token from the stream, if any found,
836 * or null to indicate end-of-input (or, for non-blocking
837 * parsers, {@link JsonToken#NOT_AVAILABLE} if no tokens were
838 * available yet)
839 */
840 public abstract JsonToken nextValue() throws IOException;
841
842 /**
843 * Method that fetches next token (as if calling {@link #nextToken}) and
844 * verifies whether it is {@link JsonToken#FIELD_NAME} with specified name
845 * and returns result of that comparison.
846 * It is functionally equivalent to:
847 *<pre>
848 * return (nextToken() == JsonToken.FIELD_NAME) && str.getValue().equals(getCurrentName());
849 *</pre>
850 * but may be faster for parser to verify, and can therefore be used if caller
851 * expects to get such a property name from input next.
852 *
853 * @param str Property name to compare next token to (if next token is
854 * <code>JsonToken.FIELD_NAME</code>)
855 */
856 public boolean nextFieldName(SerializableString str) throws IOException {
857 return (nextToken() == JsonToken.FIELD_NAME) && str.getValue().equals(getCurrentName());
858 }
859
860 /**
861 * Method that fetches next token (as if calling {@link #nextToken}) and
862 * verifies whether it is {@link JsonToken#FIELD_NAME}; if it is,
863 * returns same as {@link #getCurrentName()}, otherwise null.
864 *
865 * @since 2.5
866 */
867 public String nextFieldName() throws IOException {
868 return (nextToken() == JsonToken.FIELD_NAME) ? getCurrentName() : null;
869 }
870
871 /**
872 * Method that fetches next token (as if calling {@link #nextToken}) and
873 * if it is {@link JsonToken#VALUE_STRING} returns contained String value;
874 * otherwise returns null.
875 * It is functionally equivalent to:
876 *<pre>
877 * return (nextToken() == JsonToken.VALUE_STRING) ? getText() : null;
878 *</pre>
879 * but may be faster for parser to process, and can therefore be used if caller
880 * expects to get a String value next from input.
881 */
882 public String nextTextValue() throws IOException {
883 return (nextToken() == JsonToken.VALUE_STRING) ? getText() : null;
884 }
885
886 /**
887 * Method that fetches next token (as if calling {@link #nextToken}) and
888 * if it is {@link JsonToken#VALUE_NUMBER_INT} returns 32-bit int value;
889 * otherwise returns specified default value
890 * It is functionally equivalent to:
891 *<pre>
892 * return (nextToken() == JsonToken.VALUE_NUMBER_INT) ? getIntValue() : defaultValue;
893 *</pre>
894 * but may be faster for parser to process, and can therefore be used if caller
895 * expects to get an int value next from input.
896 */
897 public int nextIntValue(int defaultValue) throws IOException {
898 return (nextToken() == JsonToken.VALUE_NUMBER_INT) ? getIntValue() : defaultValue;
899 }
900
901 /**
902 * Method that fetches next token (as if calling {@link #nextToken}) and
903 * if it is {@link JsonToken#VALUE_NUMBER_INT} returns 64-bit long value;
904 * otherwise returns specified default value
905 * It is functionally equivalent to:
906 *<pre>
907 * return (nextToken() == JsonToken.VALUE_NUMBER_INT) ? getLongValue() : defaultValue;
908 *</pre>
909 * but may be faster for parser to process, and can therefore be used if caller
910 * expects to get a long value next from input.
911 */
912 public long nextLongValue(long defaultValue) throws IOException {
913 return (nextToken() == JsonToken.VALUE_NUMBER_INT) ? getLongValue() : defaultValue;
914 }
915
916 /**
917 * Method that fetches next token (as if calling {@link #nextToken}) and
918 * if it is {@link JsonToken#VALUE_TRUE} or {@link JsonToken#VALUE_FALSE}
919 * returns matching Boolean value; otherwise return null.
920 * It is functionally equivalent to:
921 *<pre>
922 * JsonToken t = nextToken();
923 * if (t == JsonToken.VALUE_TRUE) return Boolean.TRUE;
924 * if (t == JsonToken.VALUE_FALSE) return Boolean.FALSE;
925 * return null;
926 *</pre>
927 * but may be faster for parser to process, and can therefore be used if caller
928 * expects to get a Boolean value next from input.
929 */
930 public Boolean nextBooleanValue() throws IOException {
931 JsonToken t = nextToken();
932 if (t == JsonToken.VALUE_TRUE) { return Boolean.TRUE; }
933 if (t == JsonToken.VALUE_FALSE) { return Boolean.FALSE; }
934 return null;
935 }
936
937 /**
938 * Method that will skip all child tokens of an array or
939 * object token that the parser currently points to,
940 * iff stream points to
941 * {@link JsonToken#START_OBJECT} or {@link JsonToken#START_ARRAY}.
942 * If not, it will do nothing.
943 * After skipping, stream will point to <b>matching</b>
944 * {@link JsonToken#END_OBJECT} or {@link JsonToken#END_ARRAY}
945 * (possibly skipping nested pairs of START/END OBJECT/ARRAY tokens
946 * as well as value tokens).
947 * The idea is that after calling this method, application
948 * will call {@link #nextToken} to point to the next
949 * available token, if any.
950 */
951 public abstract JsonParser skipChildren() throws IOException;
952
953 /**
954 * Method that may be used to force full handling of the current token
955 * so that even if lazy processing is enabled, the whole contents are
956 * read for possible retrieval. This is usually used to ensure that
957 * the token end location is available, as well as token contents
958 * (similar to what calling, say {@link #getTextCharacters()}, would
959 * achieve).
960 *<p>
961 * Note that for many dataformat implementations this method
962 * will not do anything; this is the default implementation unless
963 * overridden by sub-classes.
964 *
965 * @since 2.8
966 */
967 public void finishToken() throws IOException {
968 ; // nothing
969 }
970
971 /*
972 /**********************************************************
973 /* Public API, simple token id/type access
974 /**********************************************************
975 */
976
977 /**
978 * Accessor to find which token parser currently points to, if any;
979 * null will be returned if none.
980 * If return value is non-null, data associated with the token
981 * is available via other accessor methods.
982 *
983 * @return Type of the token this parser currently points to,
984 * if any: null before any tokens have been read, and
985 * after end-of-input has been encountered, as well as
986 * if the current token has been explicitly cleared.
987 *
988 * @since 2.8
989 */
990 public JsonToken currentToken() {
991 return getCurrentToken();
992 }
993
994 /**
995 * Method similar to {@link #getCurrentToken()} but that returns an
996 * <code>int</code> instead of {@link JsonToken} (enum value).
997 *<p>
998 * Use of int directly is typically more efficient on switch statements,
999 * so this method may be useful when building low-overhead codecs.
1000 * Note, however, that effect may not be big enough to matter: make sure
1001 * to profile performance before deciding to use this method.
1002 *
1003 * @since 2.8
1004 *
1005 * @return <code>int</code> matching one of constants from {@link JsonTokenId}.
1006 */
1007 public int currentTokenId() {
1008 return getCurrentTokenId();
1009 }
1010
1011 /**
1012 * Alias for {@link #currentToken()}, will be deprecated in Jackson 2.9
1013 */
1014 public abstract JsonToken getCurrentToken();
1015
1016 /**
1017 * Alias for {@link #currentTokenId()}, will be deprecated in Jackson 2.9
1018 */
1019 public abstract int getCurrentTokenId();
1020
1021 /**
1022 * Method for checking whether parser currently points to
1023 * a token (and data for that token is available).
1024 * Equivalent to check for <code>parser.getCurrentToken() != null</code>.
1025 *
1026 * @return True if the parser just returned a valid
1027 * token via {@link #nextToken}; false otherwise (parser
1028 * was just constructed, encountered end-of-input
1029 * and returned null from {@link #nextToken}, or the token
1030 * has been consumed)
1031 */
1032 public abstract boolean hasCurrentToken();
1033
1034 /**
1035 * Method that is functionally equivalent to:
1036 *<code>
1037 * return currentTokenId() == id
1038 *</code>
1039 * but may be more efficiently implemented.
1040 *<p>
1041 * Note that no traversal or conversion is performed; so in some
1042 * cases calling method like {@link #isExpectedStartArrayToken()}
1043 * is necessary instead.
1044 *
1045 * @since 2.5
1046 */
1047 public abstract boolean hasTokenId(int id);
1048
1049 /**
1050 * Method that is functionally equivalent to:
1051 *<code>
1052 * return currentToken() == t
1053 *</code>
1054 * but may be more efficiently implemented.
1055 *<p>
1056 * Note that no traversal or conversion is performed; so in some
1057 * cases calling method like {@link #isExpectedStartArrayToken()}
1058 * is necessary instead.
1059 *
1060 * @since 2.6
1061 */
1062 public abstract boolean hasToken(JsonToken t);
1063
1064 /**
1065 * Specialized accessor that can be used to verify that the current
1066 * token indicates start array (usually meaning that current token
1067 * is {@link JsonToken#START_ARRAY}) when start array is expected.
1068 * For some specialized parsers this can return true for other cases
1069 * as well; this is usually done to emulate arrays in cases underlying
1070 * format is ambiguous (XML, for example, has no format-level difference
1071 * between Objects and Arrays; it just has elements).
1072 *<p>
1073 * Default implementation is equivalent to:
1074 *<pre>
1075 * currentToken() == JsonToken.START_ARRAY
1076 *</pre>
1077 * but may be overridden by custom parser implementations.
1078 *
1079 * @return True if the current token can be considered as a
1080 * start-array marker (such {@link JsonToken#START_ARRAY});
1081 * false if not.
1082 */
1083 public boolean isExpectedStartArrayToken() { return currentToken() == JsonToken.START_ARRAY; }
1084
1085 /**
1086 * Similar to {@link #isExpectedStartArrayToken()}, but checks whether stream
1087 * currently points to {@link JsonToken#START_OBJECT}.
1088 *
1089 * @since 2.5
1090 */
1091 public boolean isExpectedStartObjectToken() { return currentToken() == JsonToken.START_OBJECT; }
1092
1093 /**
1094 * Access for checking whether current token is a numeric value token, but
1095 * one that is of "not-a-number" (NaN) variety (including both "NaN" AND
1096 * positive/negative infinity!): not supported by all formats,
1097 * but often supported for {@link JsonToken#VALUE_NUMBER_FLOAT}.
1098 * NOTE: roughly equivalent to calling <code>!Double.isFinite()</code>
1099 * on value you would get from calling {@link #getDoubleValue()}.
1100 *
1101 * @since 2.9
1102 */
1103 public boolean isNaN() throws IOException {
1104 return false;
1105 }
1106
1107 /*
1108 /**********************************************************
1109 /* Public API, token state overrides
1110 /**********************************************************
1111 */
1112
1113 /**
1114 * Method called to "consume" the current token by effectively
1115 * removing it so that {@link #hasCurrentToken} returns false, and
1116 * {@link #getCurrentToken} null).
1117 * Cleared token value can still be accessed by calling
1118 * {@link #getLastClearedToken} (if absolutely needed), but
1119 * usually isn't.
1120 *<p>
1121 * Method was added to be used by the optional data binder, since
1122 * it has to be able to consume last token used for binding (so that
1123 * it will not be used again).
1124 */
1125 public abstract void clearCurrentToken();
1126
1127 /**
1128 * Method that can be called to get the last token that was
1129 * cleared using {@link #clearCurrentToken}. This is not necessarily
1130 * the latest token read.
1131 * Will return null if no tokens have been cleared,
1132 * or if parser has been closed.
1133 */
1134 public abstract JsonToken getLastClearedToken();
1135
1136 /**
1137 * Method that can be used to change what is considered to be
1138 * the current (field) name.
1139 * May be needed to support non-JSON data formats or unusual binding
1140 * conventions; not needed for typical processing.
1141 *<p>
1142 * Note that use of this method should only be done as sort of last
1143 * resort, as it is a work-around for regular operation.
1144 *
1145 * @param name Name to use as the current name; may be null.
1146 */
1147 public abstract void overrideCurrentName(String name);
1148
1149 /*
1150 /**********************************************************
1151 /* Public API, access to token information, text
1152 /**********************************************************
1153 */
1154
1155 /**
1156 * Method that can be called to get the name associated with
1157 * the current token: for {@link JsonToken#FIELD_NAME}s it will
1158 * be the same as what {@link #getText} returns;
1159 * for field values it will be preceding field name;
1160 * and for others (array values, root-level values) null.
1161 */
1162 public abstract String getCurrentName() throws IOException;
1163
1164 // 15-Dec-2017, tatu: Forward-looking, added in 2.9.4 (and officially in 3.0)
1165 // to smooth upgrading
1166 public String currentName() throws IOException {
1167 return getCurrentName();
1168 }
1169
1170 /**
1171 * Method for accessing textual representation of the current token;
1172 * if no current token (before first call to {@link #nextToken}, or
1173 * after encountering end-of-input), returns null.
1174 * Method can be called for any token type.
1175 */
1176 public abstract String getText() throws IOException;
1177
1178 /**
1179 * Method to read the textual representation of the current token in chunks and
1180 * pass it to the given Writer.
1181 * Conceptually same as calling:
1182 *<pre>
1183 * writer.write(parser.getText());
1184 *</pre>
1185 * but should typically be more efficient as longer content does need to
1186 * be combined into a single <code>String</code> to return, and write
1187 * can occur directly from intermediate buffers Jackson uses.
1188 *
1189 * @return The number of characters written to the Writer
1190 *
1191 * @since 2.8
1192 */
1193 public int getText(Writer writer) throws IOException, UnsupportedOperationException
1194 {
1195 String str = getText();
1196 if (str == null) {
1197 return 0;
1198 }
1199 writer.write(str);
1200 return str.length();
1201 }
1202
1203 /**
1204 * Method similar to {@link #getText}, but that will return
1205 * underlying (unmodifiable) character array that contains
1206 * textual value, instead of constructing a String object
1207 * to contain this information.
1208 * Note, however, that:
1209 *<ul>
1210 * <li>Textual contents are not guaranteed to start at
1211 * index 0 (rather, call {@link #getTextOffset}) to
1212 * know the actual offset
1213 * </li>
1214 * <li>Length of textual contents may be less than the
1215 * length of returned buffer: call {@link #getTextLength}
1216 * for actual length of returned content.
1217 * </li>
1218 * </ul>
1219 *<p>
1220 * Note that caller <b>MUST NOT</b> modify the returned
1221 * character array in any way -- doing so may corrupt
1222 * current parser state and render parser instance useless.
1223 *<p>
1224 * The only reason to call this method (over {@link #getText})
1225 * is to avoid construction of a String object (which
1226 * will make a copy of contents).
1227 */
1228 public abstract char[] getTextCharacters() throws IOException;
1229
1230 /**
1231 * Accessor used with {@link #getTextCharacters}, to know length
1232 * of String stored in returned buffer.
1233 *
1234 * @return Number of characters within buffer returned
1235 * by {@link #getTextCharacters} that are part of
1236 * textual content of the current token.
1237 */
1238 public abstract int getTextLength() throws IOException;
1239
1240 /**
1241 * Accessor used with {@link #getTextCharacters}, to know offset
1242 * of the first text content character within buffer.
1243 *
1244 * @return Offset of the first character within buffer returned
1245 * by {@link #getTextCharacters} that is part of
1246 * textual content of the current token.
1247 */
1248 public abstract int getTextOffset() throws IOException;
1249
1250 /**
1251 * Method that can be used to determine whether calling of
1252 * {@link #getTextCharacters} would be the most efficient
1253 * way to access textual content for the event parser currently
1254 * points to.
1255 *<p>
1256 * Default implementation simply returns false since only actual
1257 * implementation class has knowledge of its internal buffering
1258 * state.
1259 * Implementations are strongly encouraged to properly override
1260 * this method, to allow efficient copying of content by other
1261 * code.
1262 *
1263 * @return True if parser currently has character array that can
1264 * be efficiently returned via {@link #getTextCharacters}; false
1265 * means that it may or may not exist
1266 */
1267 public abstract boolean hasTextCharacters();
1268
1269 /*
1270 /**********************************************************
1271 /* Public API, access to token information, numeric
1272 /**********************************************************
1273 */
1274
1275 /**
1276 * Generic number value accessor method that will work for
1277 * all kinds of numeric values. It will return the optimal
1278 * (simplest/smallest possible) wrapper object that can
1279 * express the numeric value just parsed.
1280 */
1281 public abstract Number getNumberValue() throws IOException;
1282
1283 /**
1284 * If current token is of type
1285 * {@link JsonToken#VALUE_NUMBER_INT} or
1286 * {@link JsonToken#VALUE_NUMBER_FLOAT}, returns
1287 * one of {@link NumberType} constants; otherwise returns null.
1288 */
1289 public abstract NumberType getNumberType() throws IOException;
1290
1291 /**
1292 * Numeric accessor that can be called when the current
1293 * token is of type {@link JsonToken#VALUE_NUMBER_INT} and
1294 * it can be expressed as a value of Java byte primitive type.
1295 * It can also be called for {@link JsonToken#VALUE_NUMBER_FLOAT};
1296 * if so, it is equivalent to calling {@link #getDoubleValue}
1297 * and then casting; except for possible overflow/underflow
1298 * exception.
1299 *<p>
1300 * Note: if the resulting integer value falls outside range of
1301 * Java byte, a {@link JsonParseException}
1302 * will be thrown to indicate numeric overflow/underflow.
1303 */
1304 public byte getByteValue() throws IOException {
1305 int value = getIntValue();
1306 // So far so good: but does it fit?
1307 // [JACKSON-804]: Let's actually allow range of [-128, 255], as those are uniquely mapped
1308 // (instead of just signed range of [-128, 127])
1309 if (value < MIN_BYTE_I || value > MAX_BYTE_I) {
1310 throw new InputCoercionException(this,
1311 String.format("Numeric value (%s) out of range of Java byte", getText()),
1312 JsonToken.VALUE_NUMBER_INT, Byte.TYPE);
1313 }
1314 return (byte) value;
1315 }
1316
1317 /**
1318 * Numeric accessor that can be called when the current
1319 * token is of type {@link JsonToken#VALUE_NUMBER_INT} and
1320 * it can be expressed as a value of Java short primitive type.
1321 * It can also be called for {@link JsonToken#VALUE_NUMBER_FLOAT};
1322 * if so, it is equivalent to calling {@link #getDoubleValue}
1323 * and then casting; except for possible overflow/underflow
1324 * exception.
1325 *<p>
1326 * Note: if the resulting integer value falls outside range of
1327 * Java short, a {@link JsonParseException}
1328 * will be thrown to indicate numeric overflow/underflow.
1329 */
1330 public short getShortValue() throws IOException
1331 {
1332 int value = getIntValue();
1333 if (value < MIN_SHORT_I || value > MAX_SHORT_I) {
1334 throw new InputCoercionException(this,
1335 String.format("Numeric value (%s) out of range of Java short", getText()),
1336 JsonToken.VALUE_NUMBER_INT, Short.TYPE);
1337 }
1338 return (short) value;
1339 }
1340
1341 /**
1342 * Numeric accessor that can be called when the current
1343 * token is of type {@link JsonToken#VALUE_NUMBER_INT} and
1344 * it can be expressed as a value of Java int primitive type.
1345 * It can also be called for {@link JsonToken#VALUE_NUMBER_FLOAT};
1346 * if so, it is equivalent to calling {@link #getDoubleValue}
1347 * and then casting; except for possible overflow/underflow
1348 * exception.
1349 *<p>
1350 * Note: if the resulting integer value falls outside range of
1351 * Java int, a {@link JsonParseException}
1352 * may be thrown to indicate numeric overflow/underflow.
1353 */
1354 public abstract int getIntValue() throws IOException;
1355
1356 /**
1357 * Numeric accessor that can be called when the current
1358 * token is of type {@link JsonToken#VALUE_NUMBER_INT} and
1359 * it can be expressed as a Java long primitive type.
1360 * It can also be called for {@link JsonToken#VALUE_NUMBER_FLOAT};
1361 * if so, it is equivalent to calling {@link #getDoubleValue}
1362 * and then casting to int; except for possible overflow/underflow
1363 * exception.
1364 *<p>
1365 * Note: if the token is an integer, but its value falls
1366 * outside of range of Java long, a {@link JsonParseException}
1367 * may be thrown to indicate numeric overflow/underflow.
1368 */
1369 public abstract long getLongValue() throws IOException;
1370
1371 /**
1372 * Numeric accessor that can be called when the current
1373 * token is of type {@link JsonToken#VALUE_NUMBER_INT} and
1374 * it can not be used as a Java long primitive type due to its
1375 * magnitude.
1376 * It can also be called for {@link JsonToken#VALUE_NUMBER_FLOAT};
1377 * if so, it is equivalent to calling {@link #getDecimalValue}
1378 * and then constructing a {@link BigInteger} from that value.
1379 */
1380 public abstract BigInteger getBigIntegerValue() throws IOException;
1381
1382 /**
1383 * Numeric accessor that can be called when the current
1384 * token is of type {@link JsonToken#VALUE_NUMBER_FLOAT} and
1385 * it can be expressed as a Java float primitive type.
1386 * It can also be called for {@link JsonToken#VALUE_NUMBER_INT};
1387 * if so, it is equivalent to calling {@link #getLongValue}
1388 * and then casting; except for possible overflow/underflow
1389 * exception.
1390 *<p>
1391 * Note: if the value falls
1392 * outside of range of Java float, a {@link JsonParseException}
1393 * will be thrown to indicate numeric overflow/underflow.
1394 */
1395 public abstract float getFloatValue() throws IOException;
1396
1397 /**
1398 * Numeric accessor that can be called when the current
1399 * token is of type {@link JsonToken#VALUE_NUMBER_FLOAT} and
1400 * it can be expressed as a Java double primitive type.
1401 * It can also be called for {@link JsonToken#VALUE_NUMBER_INT};
1402 * if so, it is equivalent to calling {@link #getLongValue}
1403 * and then casting; except for possible overflow/underflow
1404 * exception.
1405 *<p>
1406 * Note: if the value falls
1407 * outside of range of Java double, a {@link JsonParseException}
1408 * will be thrown to indicate numeric overflow/underflow.
1409 */
1410 public abstract double getDoubleValue() throws IOException;
1411
1412 /**
1413 * Numeric accessor that can be called when the current
1414 * token is of type {@link JsonToken#VALUE_NUMBER_FLOAT} or
1415 * {@link JsonToken#VALUE_NUMBER_INT}. No under/overflow exceptions
1416 * are ever thrown.
1417 */
1418 public abstract BigDecimal getDecimalValue() throws IOException;
1419
1420 /*
1421 /**********************************************************
1422 /* Public API, access to token information, other
1423 /**********************************************************
1424 */
1425
1426 /**
1427 * Convenience accessor that can be called when the current
1428 * token is {@link JsonToken#VALUE_TRUE} or
1429 * {@link JsonToken#VALUE_FALSE}.
1430 *<p>
1431 * Note: if the token is not of above-mentioned boolean types,
1432 an integer, but its value falls
1433 * outside of range of Java long, a {@link JsonParseException}
1434 * may be thrown to indicate numeric overflow/underflow.
1435 */
1436 public boolean getBooleanValue() throws IOException {
1437 JsonToken t = currentToken();
1438 if (t == JsonToken.VALUE_TRUE) return true;
1439 if (t == JsonToken.VALUE_FALSE) return false;
1440 throw new JsonParseException(this,
1441 String.format("Current token (%s) not of boolean type", t))
1442 .withRequestPayload(_requestPayload);
1443 }
1444
1445 /**
1446 * Accessor that can be called if (and only if) the current token
1447 * is {@link JsonToken#VALUE_EMBEDDED_OBJECT}. For other token types,
1448 * null is returned.
1449 *<p>
1450 * Note: only some specialized parser implementations support
1451 * embedding of objects (usually ones that are facades on top
1452 * of non-streaming sources, such as object trees). One exception
1453 * is access to binary content (whether via base64 encoding or not)
1454 * which typically is accessible using this method, as well as
1455 * {@link #getBinaryValue()}.
1456 */
1457 public Object getEmbeddedObject() throws IOException { return null; }
1458
1459 /*
1460 /**********************************************************
1461 /* Public API, access to token information, binary
1462 /**********************************************************
1463 */
1464
1465 /**
1466 * Method that can be used to read (and consume -- results
1467 * may not be accessible using other methods after the call)
1468 * base64-encoded binary data
1469 * included in the current textual JSON value.
1470 * It works similar to getting String value via {@link #getText}
1471 * and decoding result (except for decoding part),
1472 * but should be significantly more performant.
1473 *<p>
1474 * Note that non-decoded textual contents of the current token
1475 * are not guaranteed to be accessible after this method
1476 * is called. Current implementation, for example, clears up
1477 * textual content during decoding.
1478 * Decoded binary content, however, will be retained until
1479 * parser is advanced to the next event.
1480 *
1481 * @param bv Expected variant of base64 encoded
1482 * content (see {@link Base64Variants} for definitions
1483 * of "standard" variants).
1484 *
1485 * @return Decoded binary data
1486 */
1487 public abstract byte[] getBinaryValue(Base64Variant bv) throws IOException;
1488
1489 /**
1490 * Convenience alternative to {@link #getBinaryValue(Base64Variant)}
1491 * that defaults to using
1492 * {@link Base64Variants#getDefaultVariant} as the default encoding.
1493 */
1494 public byte[] getBinaryValue() throws IOException {
1495 return getBinaryValue(Base64Variants.getDefaultVariant());
1496 }
1497
1498 /**
1499 * Method that can be used as an alternative to {@link #getBigIntegerValue()},
1500 * especially when value can be large. The main difference (beyond method
1501 * of returning content using {@link OutputStream} instead of as byte array)
1502 * is that content will NOT remain accessible after method returns: any content
1503 * processed will be consumed and is not buffered in any way. If caller needs
1504 * buffering, it has to implement it.
1505 *
1506 * @param out Output stream to use for passing decoded binary data
1507 *
1508 * @return Number of bytes that were decoded and written via {@link OutputStream}
1509 *
1510 * @since 2.1
1511 */
1512 public int readBinaryValue(OutputStream out) throws IOException {
1513 return readBinaryValue(Base64Variants.getDefaultVariant(), out);
1514 }
1515
1516 /**
1517 * Similar to {@link #readBinaryValue(OutputStream)} but allows explicitly
1518 * specifying base64 variant to use.
1519 *
1520 * @param bv base64 variant to use
1521 * @param out Output stream to use for passing decoded binary data
1522 *
1523 * @return Number of bytes that were decoded and written via {@link OutputStream}
1524 *
1525 * @since 2.1
1526 */
1527 public int readBinaryValue(Base64Variant bv, OutputStream out) throws IOException {
1528 _reportUnsupportedOperation();
1529 return 0; // never gets here
1530 }
1531
1532 /*
1533 /**********************************************************
1534 /* Public API, access to token information, coercion/conversion
1535 /**********************************************************
1536 */
1537
1538 /**
1539 * Method that will try to convert value of current token to a
1540 * <b>int</b>.
1541 * Numbers are coerced using default Java rules; booleans convert to 0 (false)
1542 * and 1 (true), and Strings are parsed using default Java language integer
1543 * parsing rules.
1544 *<p>
1545 * If representation can not be converted to an int (including structured type
1546 * markers like start/end Object/Array)
1547 * default value of <b>0</b> will be returned; no exceptions are thrown.
1548 */
1549 public int getValueAsInt() throws IOException {
1550 return getValueAsInt(0);
1551 }
1552
1553 /**
1554 * Method that will try to convert value of current token to a
1555 * <b>int</b>.
1556 * Numbers are coerced using default Java rules; booleans convert to 0 (false)
1557 * and 1 (true), and Strings are parsed using default Java language integer
1558 * parsing rules.
1559 *<p>
1560 * If representation can not be converted to an int (including structured type
1561 * markers like start/end Object/Array)
1562 * specified <b>def</b> will be returned; no exceptions are thrown.
1563 */
1564 public int getValueAsInt(int def) throws IOException { return def; }
1565
1566 /**
1567 * Method that will try to convert value of current token to a
1568 * <b>long</b>.
1569 * Numbers are coerced using default Java rules; booleans convert to 0 (false)
1570 * and 1 (true), and Strings are parsed using default Java language integer
1571 * parsing rules.
1572 *<p>
1573 * If representation can not be converted to a long (including structured type
1574 * markers like start/end Object/Array)
1575 * default value of <b>0L</b> will be returned; no exceptions are thrown.
1576 */
1577 public long getValueAsLong() throws IOException {
1578 return getValueAsLong(0);
1579 }
1580
1581 /**
1582 * Method that will try to convert value of current token to a
1583 * <b>long</b>.
1584 * Numbers are coerced using default Java rules; booleans convert to 0 (false)
1585 * and 1 (true), and Strings are parsed using default Java language integer
1586 * parsing rules.
1587 *<p>
1588 * If representation can not be converted to a long (including structured type
1589 * markers like start/end Object/Array)
1590 * specified <b>def</b> will be returned; no exceptions are thrown.
1591 */
1592 public long getValueAsLong(long def) throws IOException {
1593 return def;
1594 }
1595
1596 /**
1597 * Method that will try to convert value of current token to a Java
1598 * <b>double</b>.
1599 * Numbers are coerced using default Java rules; booleans convert to 0.0 (false)
1600 * and 1.0 (true), and Strings are parsed using default Java language floating
1601 * point parsing rules.
1602 *<p>
1603 * If representation can not be converted to a double (including structured types
1604 * like Objects and Arrays),
1605 * default value of <b>0.0</b> will be returned; no exceptions are thrown.
1606 */
1607 public double getValueAsDouble() throws IOException {
1608 return getValueAsDouble(0.0);
1609 }
1610
1611 /**
1612 * Method that will try to convert value of current token to a
1613 * Java <b>double</b>.
1614 * Numbers are coerced using default Java rules; booleans convert to 0.0 (false)
1615 * and 1.0 (true), and Strings are parsed using default Java language floating
1616 * point parsing rules.
1617 *<p>
1618 * If representation can not be converted to a double (including structured types
1619 * like Objects and Arrays),
1620 * specified <b>def</b> will be returned; no exceptions are thrown.
1621 */
1622 public double getValueAsDouble(double def) throws IOException {
1623 return def;
1624 }
1625
1626 /**
1627 * Method that will try to convert value of current token to a
1628 * <b>boolean</b>.
1629 * JSON booleans map naturally; integer numbers other than 0 map to true, and
1630 * 0 maps to false
1631 * and Strings 'true' and 'false' map to corresponding values.
1632 *<p>
1633 * If representation can not be converted to a boolean value (including structured types
1634 * like Objects and Arrays),
1635 * default value of <b>false</b> will be returned; no exceptions are thrown.
1636 */
1637 public boolean getValueAsBoolean() throws IOException {
1638 return getValueAsBoolean(false);
1639 }
1640
1641 /**
1642 * Method that will try to convert value of current token to a
1643 * <b>boolean</b>.
1644 * JSON booleans map naturally; integer numbers other than 0 map to true, and
1645 * 0 maps to false
1646 * and Strings 'true' and 'false' map to corresponding values.
1647 *<p>
1648 * If representation can not be converted to a boolean value (including structured types
1649 * like Objects and Arrays),
1650 * specified <b>def</b> will be returned; no exceptions are thrown.
1651 */
1652 public boolean getValueAsBoolean(boolean def) throws IOException {
1653 return def;
1654 }
1655
1656 /**
1657 * Method that will try to convert value of current token to a
1658 * {@link java.lang.String}.
1659 * JSON Strings map naturally; scalar values get converted to
1660 * their textual representation.
1661 * If representation can not be converted to a String value (including structured types
1662 * like Objects and Arrays and null token), default value of
1663 * <b>null</b> will be returned; no exceptions are thrown.
1664 *
1665 * @since 2.1
1666 */
1667 public String getValueAsString() throws IOException {
1668 return getValueAsString(null);
1669 }
1670
1671 /**
1672 * Method that will try to convert value of current token to a
1673 * {@link java.lang.String}.
1674 * JSON Strings map naturally; scalar values get converted to
1675 * their textual representation.
1676 * If representation can not be converted to a String value (including structured types
1677 * like Objects and Arrays and null token), specified default value
1678 * will be returned; no exceptions are thrown.
1679 *
1680 * @since 2.1
1681 */
1682 public abstract String getValueAsString(String def) throws IOException;
1683
1684 /*
1685 /**********************************************************
1686 /* Public API, Native Ids (type, object)
1687 /**********************************************************
1688 */
1689
1690 /**
1691 * Introspection method that may be called to see if the underlying
1692 * data format supports some kind of Object Ids natively (many do not;
1693 * for example, JSON doesn't).
1694 *<p>
1695 * Default implementation returns true; overridden by data formats
1696 * that do support native Object Ids. Caller is expected to either
1697 * use a non-native notation (explicit property or such), or fail,
1698 * in case it can not use native object ids.
1699 *
1700 * @since 2.3
1701 */
1702 public boolean canReadObjectId() { return false; }
1703
1704 /**
1705 * Introspection method that may be called to see if the underlying
1706 * data format supports some kind of Type Ids natively (many do not;
1707 * for example, JSON doesn't).
1708 *<p>
1709 * Default implementation returns true; overridden by data formats
1710 * that do support native Type Ids. Caller is expected to either
1711 * use a non-native notation (explicit property or such), or fail,
1712 * in case it can not use native type ids.
1713 *
1714 * @since 2.3
1715 */
1716 public boolean canReadTypeId() { return false; }
1717
1718 /**
1719 * Method that can be called to check whether current token
1720 * (one that was just read) has an associated Object id, and if
1721 * so, return it.
1722 * Note that while typically caller should check with {@link #canReadObjectId}
1723 * first, it is not illegal to call this method even if that method returns
1724 * true; but if so, it will return null. This may be used to simplify calling
1725 * code.
1726 *<p>
1727 * Default implementation will simply return null.
1728 *
1729 * @since 2.3
1730 */
1731 public Object getObjectId() throws IOException { return null; }
1732
1733 /**
1734 * Method that can be called to check whether current token
1735 * (one that was just read) has an associated type id, and if
1736 * so, return it.
1737 * Note that while typically caller should check with {@link #canReadTypeId}
1738 * first, it is not illegal to call this method even if that method returns
1739 * true; but if so, it will return null. This may be used to simplify calling
1740 * code.
1741 *<p>
1742 * Default implementation will simply return null.
1743 *
1744 * @since 2.3
1745 */
1746 public Object getTypeId() throws IOException { return null; }
1747
1748 /*
1749 /**********************************************************
1750 /* Public API, optional data binding functionality
1751 /**********************************************************
1752 */
1753
1754 /**
1755 * Method to deserialize JSON content into a non-container
1756 * type (it can be an array type, however): typically a bean, array
1757 * or a wrapper type (like {@link java.lang.Boolean}).
1758 * <b>Note</b>: method can only be called if the parser has
1759 * an object codec assigned; this is true for parsers constructed
1760 * by <code>MappingJsonFactory</code> (from "jackson-databind" jar)
1761 * but not for {@link JsonFactory} (unless its <code>setCodec</code>
1762 * method has been explicitly called).
1763 *<p>
1764 * This method may advance the event stream, for structured types
1765 * the current token will be the closing end marker (END_ARRAY,
1766 * END_OBJECT) of the bound structure. For non-structured Json types
1767 * (and for {@link JsonToken#VALUE_EMBEDDED_OBJECT})
1768 * stream is not advanced.
1769 *<p>
1770 * Note: this method should NOT be used if the result type is a
1771 * container ({@link java.util.Collection} or {@link java.util.Map}.
1772 * The reason is that due to type erasure, key and value types
1773 * can not be introspected when using this method.
1774 */
1775 public <T> T readValueAs(Class<T> valueType) throws IOException {
1776 return _codec().readValue(this, valueType);
1777 }
1778
1779 /**
1780 * Method to deserialize JSON content into a Java type, reference
1781 * to which is passed as argument. Type is passed using so-called
1782 * "super type token"
1783 * and specifically needs to be used if the root type is a
1784 * parameterized (generic) container type.
1785 * <b>Note</b>: method can only be called if the parser has
1786 * an object codec assigned; this is true for parsers constructed
1787 * by <code>MappingJsonFactory</code> (defined in 'jackson-databind' bundle)
1788 * but not for {@link JsonFactory} (unless its <code>setCodec</code>
1789 * method has been explicitly called).
1790 *<p>
1791 * This method may advance the event stream, for structured types
1792 * the current token will be the closing end marker (END_ARRAY,
1793 * END_OBJECT) of the bound structure. For non-structured Json types
1794 * (and for {@link JsonToken#VALUE_EMBEDDED_OBJECT})
1795 * stream is not advanced.
1796 */
1797 @SuppressWarnings("unchecked")
1798 public <T> T readValueAs(TypeReference<?> valueTypeRef) throws IOException {
1799 return (T) _codec().readValue(this, valueTypeRef);
1800 }
1801
1802 /**
1803 * Method for reading sequence of Objects from parser stream,
1804 * all with same specified value type.
1805 */
1806 public <T> Iterator<T> readValuesAs(Class<T> valueType) throws IOException {
1807 return _codec().readValues(this, valueType);
1808 }
1809
1810 /**
1811 * Method for reading sequence of Objects from parser stream,
1812 * all with same specified value type.
1813 */
1814 public <T> Iterator<T> readValuesAs(TypeReference<T> valueTypeRef) throws IOException {
1815 return _codec().readValues(this, valueTypeRef);
1816 }
1817
1818 /**
1819 * Method to deserialize JSON content into equivalent "tree model",
1820 * represented by root {@link TreeNode} of resulting model.
1821 * For JSON Arrays it will an array node (with child nodes),
1822 * for objects object node (with child nodes), and for other types
1823 * matching leaf node type. Empty or whitespace documents are null.
1824 *
1825 * @return root of the document, or null if empty or whitespace.
1826 */
1827 @SuppressWarnings("unchecked")
1828 public <T extends TreeNode> T readValueAsTree() throws IOException {
1829 return (T) _codec().readTree(this);
1830 }
1831
1832 protected ObjectCodec _codec() {
1833 ObjectCodec c = getCodec();
1834 if (c == null) {
1835 throw new IllegalStateException("No ObjectCodec defined for parser, needed for deserialization");
1836 }
1837 return c;
1838 }
1839
1840 /*
1841 /**********************************************************
1842 /* Internal methods
1843 /**********************************************************
1844 */
1845
1846 /**
1847 * Helper method for constructing {@link JsonParseException}s
1848 * based on current state of the parser
1849 */
1850 protected JsonParseException _constructError(String msg) {
1851 return new JsonParseException(this, msg)
1852 .withRequestPayload(_requestPayload);
1853 }
1854
1855 /**
1856 * Helper method to call for operations that are not supported by
1857 * parser implementation.
1858 *
1859 * @since 2.1
1860 */
1861 protected void _reportUnsupportedOperation() {
1862 throw new UnsupportedOperationException("Operation not supported by parser of type "+getClass().getName());
1863 }
1864 }
1865