-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
ObjectMapper.java
2548 lines (2337 loc) · 104 KB
/
ObjectMapper.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package com.fasterxml.jackson.databind;
import java.io.*;
import java.lang.reflect.Type;
import java.net.URL;
import java.text.DateFormat;
import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicReference;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.core.io.CharacterEscapes;
import com.fasterxml.jackson.core.io.SegmentedStringWriter;
import com.fasterxml.jackson.core.json.JsonFactory;
import com.fasterxml.jackson.core.type.ResolvedType;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.core.util.*;
import com.fasterxml.jackson.databind.cfg.*;
import com.fasterxml.jackson.databind.deser.*;
import com.fasterxml.jackson.databind.exc.MismatchedInputException;
import com.fasterxml.jackson.databind.introspect.*;
import com.fasterxml.jackson.databind.jsonFormatVisitors.JsonFormatVisitorWrapper;
import com.fasterxml.jackson.databind.jsontype.SubtypeResolver;
import com.fasterxml.jackson.databind.node.*;
import com.fasterxml.jackson.databind.ser.*;
import com.fasterxml.jackson.databind.type.*;
import com.fasterxml.jackson.databind.util.ClassUtil;
import com.fasterxml.jackson.databind.util.RootNameLookup;
import com.fasterxml.jackson.databind.util.TokenBuffer;
/**
* ObjectMapper provides functionality for reading and writing JSON,
* either to and from basic POJOs (Plain Old Java Objects), or to and from
* a general-purpose JSON Tree Model ({@link JsonNode}), as well as
* related functionality for performing conversions.
* In addition to directly reading and writing JSON (and with different underlying
* {@link TokenStreamFactory} configuration, other formats), it is also the
* mechanism for creating {@link ObjectReader}s and {@link ObjectWriter}s which
* offer more advancing reading/writing functionality.
*<p>
* Construction of mapper instances proceeds either via no-arguments constructor
* (producing instance with default configuration); or through one of two build
* methods.
* First build method is the static <code>builder()</code> on exact type
* and second {@link #rebuild()} method method on an existing mapper.
* Former starts with default configuration (same as one that no-arguments constructor
* created mapper has), and latter starts with configuration of the mapper it is called
* on.
* In both cases, after configuration (including addition of {@link Module}s) is complete,
* instance is created by calling {@link MapperBuilder#build()} method.
*<p>
* Mapper (and {@link ObjectReader}s, {@link ObjectWriter}s it constructs) will
* use instances of {@link JsonParser} and {@link JsonGenerator}
* for implementing actual reading/writing of JSON.
* Note that although most read and write methods are exposed through this class,
* some of the functionality is only exposed via {@link ObjectReader} and
* {@link ObjectWriter}: specifically, reading/writing of longer sequences of
* values is only available through {@link ObjectReader#readValues(InputStream)}
* and {@link ObjectWriter#writeValues(OutputStream)}.
*<p>
Simplest usage is of form:
<pre>
final ObjectMapper mapper = new ObjectMapper(); // can use static singleton, inject: just make sure to reuse!
MyValue value = new MyValue();
// ... and configure
File newState = new File("my-stuff.json");
mapper.writeValue(newState, value); // writes JSON serialization of MyValue instance
// or, read
MyValue older = mapper.readValue(new File("my-older-stuff.json"), MyValue.class);
// Or if you prefer JSON Tree representation:
JsonNode root = mapper.readTree(newState);
// and find values by, for example, using a {@link com.fasterxml.jackson.core.JsonPointer} expression:
int age = root.at("/personal/age").getValueAsInt();
</pre>
*<p>
* Mapper instances are fully thread-safe as of Jackson 3.0.
*<p>
* Note on caching: root-level deserializers are always cached, and accessed
* using full (generics-aware) type information. This is different from
* caching of referenced types, which is more limited and is done only
* for a subset of all deserializer types. The main reason for difference
* is that at root-level there is no incoming reference (and hence no
* referencing property, no referral information or annotations to
* produce differing deserializers), and that the performance impact
* greatest at root level (since it'll essentially cache the full
* graph of deserializers involved).
*/
public class ObjectMapper
implements Versioned,
java.io.Serializable
{
private static final long serialVersionUID = 3L;
/*
/**********************************************************************
/* Helper classes, enums
/**********************************************************************
*/
/**
* Base implementation for "Vanilla" {@link ObjectMapper}, only defined to support
* backwards-compatibility with some of 2.x usage patterns.
*/
private static class PrivateBuilder extends MapperBuilder<ObjectMapper, PrivateBuilder>
{
public PrivateBuilder(TokenStreamFactory tsf) {
super(tsf);
}
@Override
public ObjectMapper build() {
return new ObjectMapper(this);
}
@Override
protected MapperBuilderState _saveState() {
return new StateImpl(this);
}
public PrivateBuilder(MapperBuilderState state) {
super(state);
}
// We also need actual instance of state as base class can not implement logic
// for reinstating mapper (via mapper builder) from state.
static class StateImpl extends MapperBuilderState {
private static final long serialVersionUID = 3L;
public StateImpl(PrivateBuilder b) {
super(b);
}
@Override
protected Object readResolve() {
return new PrivateBuilder(this).build();
}
}
}
/*
/**********************************************************************
/* Internal constants, singletons
/**********************************************************************
*/
// Quick little shortcut, to avoid having to use global TypeFactory instance...
// 19-Oct-2015, tatu: Not sure if this is really safe to do; let's at least allow
// some amount of introspection
private final static JavaType JSON_NODE_TYPE =
SimpleType.constructUnsafe(JsonNode.class);
// TypeFactory.defaultInstance().constructType(JsonNode.class);
/*
/**********************************************************************
/* Configuration settings, shared
/**********************************************************************
*/
/**
* Factory used to create {@link JsonParser} and {@link JsonGenerator}
* instances as necessary.
*/
protected final TokenStreamFactory _streamFactory;
/**
* Specific factory used for creating {@link JavaType} instances;
* needed to allow modules to add more custom type handling
* (mostly to support types of non-Java JVM languages)
*/
protected final TypeFactory _typeFactory;
/**
* Provider for values to inject in deserialized POJOs.
*/
protected final InjectableValues _injectableValues;
/*
/**********************************************************************
/* Configuration settings, serialization
/**********************************************************************
*/
/**
* Factory used for constructing per-call {@link SerializerProvider}s.
*<p>
* Note: while serializers are only exposed {@link SerializerProvider},
* mappers and readers need to access additional API defined by
* {@link DefaultSerializerProvider}
*/
protected final SerializationContexts _serializationContexts;
/**
* Configuration object that defines basic global
* settings for the serialization process
*/
protected final SerializationConfig _serializationConfig;
/*
/**********************************************************************
/* Configuration settings, deserialization
/**********************************************************************
*/
/**
* Factory used for constructing per-call {@link DeserializationContext}s.
*/
protected final DeserializationContexts _deserializationContexts;
/**
* Configuration object that defines basic global
* settings for the serialization process
*/
protected final DeserializationConfig _deserializationConfig;
/*
/**********************************************************************
/* Caching
/**********************************************************************
*/
/* Note: handling of serializers and deserializers is not symmetric;
* and as a result, only root-level deserializers can be cached here.
* This is mostly because typing and resolution for deserializers is
* fully static; whereas it is quite dynamic for serialization.
*/
/**
* We will use a separate main-level Map for keeping track
* of root-level deserializers. This is where most successful
* cache lookups get resolved.
* Map will contain resolvers for all kinds of types, including
* container types: this is different from the component cache
* which will only cache bean deserializers.
*<p>
* Given that we don't expect much concurrency for additions
* (should very quickly converge to zero after startup), let's
* explicitly define a low concurrency setting.
*<p>
* These may are either "raw" deserializers (when
* no type information is needed for base type), or type-wrapped
* deserializers (if it is needed)
*/
protected final ConcurrentHashMap<JavaType, JsonDeserializer<Object>> _rootDeserializers
= new ConcurrentHashMap<JavaType, JsonDeserializer<Object>>(64, 0.6f, 2);
/*
/**********************************************************************
/* Saved state to allow re-building
/**********************************************************************
*/
/**
* Minimal state retained to allow both re-building (by
* creating new builder) and JDK serialization of this mapper.
*
* @since 3.0
*/
protected final MapperBuilderState _savedBuilderState;
/*
/**********************************************************************
/* Life-cycle: legacy constructors
/**********************************************************************
*/
/**
* Default constructor, which will construct the default JSON-handling
* {@link TokenStreamFactory} as necessary and all other unmodified
* default settings, and no additional registered modules.
*/
public ObjectMapper() {
this(new PrivateBuilder(new JsonFactory()));
}
/**
* Constructs instance that uses specified {@link TokenStreamFactory}
* for constructing necessary {@link JsonParser}s and/or
* {@link JsonGenerator}s, but without registering additional modules.
*/
public ObjectMapper(TokenStreamFactory streamFactory) {
this(new PrivateBuilder(streamFactory));
}
/*
/**********************************************************************
/* Life-cycle: builder-style construction
/**********************************************************************
*/
/**
* Constructor usually called either by {@link MapperBuilder#build} or
* by sub-class constructor: will get all the settings through passed-in
* builder, including registration of any modules added to builder.
*/
protected ObjectMapper(MapperBuilder<?,?> builder)
{
// First things first: finalize building process. Saved state
// consists of snapshots and is safe to keep references to; used
// for rebuild()ing mapper instances
_savedBuilderState = builder.saveStateApplyModules();
// But we will ALSO need to take snapshot of anything builder has,
// in case caller keeps on tweaking with builder. So rules are the
// as with above call, or when creating new builder for rebuild()ing
// General framework factories
_streamFactory = builder.streamFactory();
final ConfigOverrides configOverrides;
{
// bit tricky as we do NOT want to expose simple accessors (to a mutable thing)
final AtomicReference<ConfigOverrides> ref = new AtomicReference<>();
builder.withAllConfigOverrides(overrides -> ref.set(overrides));
configOverrides = Snapshottable.takeSnapshot(ref.get());
}
// Handlers, introspection
_typeFactory = Snapshottable.takeSnapshot(builder.typeFactory());
ClassIntrospector classIntr = builder.classIntrospector().forMapper(this);
SubtypeResolver subtypeResolver = Snapshottable.takeSnapshot(builder.subtypeResolver());
MixInHandler mixIns = (MixInHandler) Snapshottable.takeSnapshot(builder.mixInHandler());
// NOTE: TypeResolverProvider apparently ok without snapshot, hence config objects fetch
// it directly from MapperBuilder, not passed by us.
// Serialization factories
_serializationContexts = builder.serializationContexts()
.forMapper(this, _streamFactory, builder.serializerFactory());
// Deserialization factories
_deserializationContexts = builder.deserializationContexts()
.forMapper(this, _streamFactory, builder.deserializerFactory());
_injectableValues = Snapshottable.takeSnapshot(builder.injectableValues());
// And then finalize serialization/deserialization Config containers
RootNameLookup rootNames = new RootNameLookup();
FilterProvider filterProvider = Snapshottable.takeSnapshot(builder.filterProvider());
_deserializationConfig = builder.buildDeserializationConfig(configOverrides,
mixIns, _typeFactory, classIntr, subtypeResolver,
rootNames);
_serializationConfig = builder.buildSerializationConfig(configOverrides,
mixIns, _typeFactory, classIntr, subtypeResolver,
rootNames, filterProvider);
}
/**
* Method for creating a new {@link MapperBuilder} for constructing differently configured
* {@link ObjectMapper} instance, starting with current configuration including base settings
* and registered modules.
*
* @since 3.0
*/
@SuppressWarnings("unchecked")
public <M extends ObjectMapper, B extends MapperBuilder<M,B>> MapperBuilder<M,B> rebuild() {
// 27-Feb-2018, tatu: since we still have problem with `ObjectMapper` being both API
// and implementation for JSON, need more checking here
ClassUtil.verifyMustOverride(ObjectMapper.class, this, "rebuild");
return (MapperBuilder<M,B>) new PrivateBuilder(_savedBuilderState);
}
/*
/**********************************************************************
/* Life-cycle: JDK serialization support
/**********************************************************************
*/
// Logic here is simple: instead of serializing mapper via its contents,
// we have pre-packaged `MapperBuilderState` in a way that makes serialization
// easier, and we go with that.
// But note that return direction has to be supported, then, by that state object
// and NOT anything in here.
protected Object writeReplace() {
return _savedBuilderState;
}
// Just as a sanity check verify there is no attempt at directly instantiating mapper here
protected Object readResolve() {
throw new IllegalStateException("Should never deserialize `"+getClass().getName()+"` directly");
}
/*
/**********************************************************************
/* Versioned impl
/**********************************************************************
*/
/**
* Method that will return version information stored in and read from jar
* that contains this class.
*/
@Override
public Version version() {
return com.fasterxml.jackson.databind.cfg.PackageVersion.VERSION;
}
/*
/**********************************************************************
/* Configuration: main config object access
/**********************************************************************
*/
/**
* Accessor for internal configuration object that contains settings for
* serialization operations (<code>writeValue(...)</code> methods)
*<br>
* NOTE: Not to be used by application code; needed by some tests
*/
public SerializationConfig serializationConfig() {
return _serializationConfig;
}
/**
* Accessor for internal configuration object that contains settings for
* deserialization operations (<code>readValue(...)</code> methods)
*<br>
* NOTE: Not to be used by application code; needed by some tests
*/
public DeserializationConfig deserializationConfig() {
return _deserializationConfig;
}
/**
* Method that can be used to get hold of {@link TokenStreamFactory} that this
* mapper uses if it needs to construct {@link JsonParser}s
* and/or {@link JsonGenerator}s.
*<p>
* WARNING: note that all {@link ObjectReader} and {@link ObjectWriter}
* instances created by this mapper usually share the same configured
* {@link TokenStreamFactory}, so changes to its configuration will "leak".
* To avoid such observed changes you should always use "with()" and
* "without()" method of {@link ObjectReader} and {@link ObjectWriter}
* for changing {@link StreamReadFeature}
* and {@link StreamWriteFeature}
* settings to use on per-call basis.
*
* @return {@link TokenStreamFactory} that this mapper uses when it needs to
* construct Json parser and generators
*
* @since 3.0
*/
public TokenStreamFactory tokenStreamFactory() { return _streamFactory; }
/**
* Method that can be used to get hold of {@link JsonNodeFactory}
* that this mapper will use when directly constructing
* root {@link JsonNode} instances for Trees.
*<p>
* Note: this is just a shortcut for calling
*<pre>
* getDeserializationConfig().getNodeFactory()
*</pre>
*/
public JsonNodeFactory getNodeFactory() {
return _deserializationConfig.getNodeFactory();
}
public InjectableValues getInjectableValues() {
return _injectableValues;
}
/*
/**********************************************************************
/* Configuration, access to type factory, type resolution
/**********************************************************************
*/
/**
* Accessor for getting currently configured {@link TypeFactory} instance.
*/
public TypeFactory getTypeFactory() {
return _typeFactory;
}
/**
* Convenience method for constructing {@link JavaType} out of given
* type (typically <code>java.lang.Class</code>), but without explicit
* context.
*/
public JavaType constructType(Type t) {
return _typeFactory.constructType(t);
}
/*
/**********************************************************************
/* Configuration, accessing features
/**********************************************************************
*/
public boolean isEnabled(JsonFactory.Feature f) {
return _streamFactory.isEnabled(f);
}
public boolean isEnabled(StreamReadFeature f) {
return _deserializationConfig.isEnabled(f);
}
public boolean isEnabled(StreamWriteFeature f) {
return _serializationConfig.isEnabled(f);
}
/**
* Method for checking whether given {@link MapperFeature} is enabled.
*/
public boolean isEnabled(MapperFeature f) {
// ok to use either one, should be kept in sync
return _serializationConfig.isEnabled(f);
}
/**
* Method for checking whether given deserialization-specific
* feature is enabled.
*/
public boolean isEnabled(DeserializationFeature f) {
return _deserializationConfig.isEnabled(f);
}
/**
* Method for checking whether given serialization-specific
* feature is enabled.
*/
public boolean isEnabled(SerializationFeature f) {
return _serializationConfig.isEnabled(f);
}
/*
/**********************************************************************
/* Configuration, accessing module information
/**********************************************************************
*/
/**
* Method that may be used to find out {@link Module}s that were registered
* when creating this mapper (if any).
*
* @since 3.0
*/
public Collection<com.fasterxml.jackson.databind.Module> getRegisteredModules() {
return _savedBuilderState.modules();
}
/*
/**********************************************************************
/* Public API: constructing Parsers that are properly linked
/* to `ObjectReadContext`
/**********************************************************************
*/
/**
* Factory method for constructing {@link JsonParser} that is properly
* wired to allow callbacks for deserialization: basically
* constructs a {@link ObjectReadContext} and then calls
* {@link TokenStreamFactory#createParser(ObjectReadContext,java.io.File)}.
*
* @since 3.0
*/
public JsonParser createParser(File src) throws IOException {
DefaultDeserializationContext ctxt = createDeserializationContext();
return ctxt.assignAndReturnParser(_streamFactory.createParser(ctxt, src));
}
/**
* Factory method for constructing {@link JsonParser} that is properly
* wired to allow callbacks for deserialization: basically
* constructs a {@link ObjectReadContext} and then calls
* {@link TokenStreamFactory#createParser(ObjectReadContext,java.net.URL)}.
*
* @since 3.0
*/
public JsonParser createParser(URL src) throws IOException {
DefaultDeserializationContext ctxt = createDeserializationContext();
return ctxt.assignAndReturnParser(_streamFactory.createParser(ctxt, src));
}
/**
* Factory method for constructing {@link JsonParser} that is properly
* wired to allow callbacks for deserialization: basically
* constructs a {@link ObjectReadContext} and then calls
* {@link TokenStreamFactory#createParser(ObjectReadContext,InputStream)}.
*
* @since 3.0
*/
public JsonParser createParser(InputStream in) throws IOException {
DefaultDeserializationContext ctxt = createDeserializationContext();
return ctxt.assignAndReturnParser(_streamFactory.createParser(ctxt, in));
}
/**
* Factory method for constructing {@link JsonParser} that is properly
* wired to allow callbacks for deserialization: basically
* constructs a {@link ObjectReadContext} and then calls
* {@link TokenStreamFactory#createParser(ObjectReadContext,Reader)}.
*
* @since 3.0
*/
public JsonParser createParser(Reader r) throws IOException {
DefaultDeserializationContext ctxt = createDeserializationContext();
return ctxt.assignAndReturnParser(_streamFactory.createParser(ctxt, r));
}
/**
* Factory method for constructing {@link JsonParser} that is properly
* wired to allow callbacks for deserialization: basically
* constructs a {@link ObjectReadContext} and then calls
* {@link TokenStreamFactory#createParser(ObjectReadContext,byte[])}.
*
* @since 3.0
*/
public JsonParser createParser(byte[] data) throws IOException {
DefaultDeserializationContext ctxt = createDeserializationContext();
return ctxt.assignAndReturnParser(_streamFactory.createParser(ctxt, data));
}
/**
* Factory method for constructing {@link JsonParser} that is properly
* wired to allow callbacks for deserialization: basically
* constructs a {@link ObjectReadContext} and then calls
* {@link TokenStreamFactory#createParser(ObjectReadContext,byte[],int,int)}.
*
* @since 3.0
*/
public JsonParser createParser(byte[] data, int offset, int len) throws IOException {
DefaultDeserializationContext ctxt = createDeserializationContext();
return ctxt.assignAndReturnParser(_streamFactory.createParser(ctxt, data, offset, len));
}
/**
* Factory method for constructing {@link JsonParser} that is properly
* wired to allow callbacks for deserialization: basically
* constructs a {@link ObjectReadContext} and then calls
* {@link TokenStreamFactory#createParser(ObjectReadContext,String)}.
*
* @since 3.0
*/
public JsonParser createParser(String content) throws IOException {
DefaultDeserializationContext ctxt = createDeserializationContext();
return ctxt.assignAndReturnParser(_streamFactory.createParser(ctxt, content));
}
/**
* Factory method for constructing {@link JsonParser} that is properly
* wired to allow callbacks for deserialization: basically
* constructs a {@link ObjectReadContext} and then calls
* {@link TokenStreamFactory#createParser(ObjectReadContext,char[])}.
*
* @since 3.0
*/
public JsonParser createParser(char[] content) throws IOException {
DefaultDeserializationContext ctxt = createDeserializationContext();
return ctxt.assignAndReturnParser(_streamFactory.createParser(ctxt, content));
}
/**
* Factory method for constructing {@link JsonParser} that is properly
* wired to allow callbacks for deserialization: basically
* constructs a {@link ObjectReadContext} and then calls
* {@link TokenStreamFactory#createParser(ObjectReadContext,char[],int,int)}.
*
* @since 3.0
*/
public JsonParser createParser(char[] content, int offset, int len) throws IOException {
DefaultDeserializationContext ctxt = createDeserializationContext();
return ctxt.assignAndReturnParser(_streamFactory.createParser(ctxt, content, offset, len));
}
/**
* Factory method for constructing {@link JsonParser} that is properly
* wired to allow callbacks for deserialization: basically
* constructs a {@link ObjectReadContext} and then calls
* {@link TokenStreamFactory#createParser(ObjectReadContext,DataInput)}.
*
* @since 3.0
*/
public JsonParser createParser(DataInput content) throws IOException {
DefaultDeserializationContext ctxt = createDeserializationContext();
return ctxt.assignAndReturnParser(_streamFactory.createParser(ctxt, content));
}
/**
* Factory method for constructing non-blocking {@link JsonParser} that is properly
* wired to allow configuration access (and, if relevant for parser, callbacks):
* essentially constructs a {@link ObjectReadContext} and then calls
* {@link TokenStreamFactory#createParser(ObjectReadContext,DataInput)}.
*
* @since 3.0
*/
public JsonParser createNonBlockingByteArrayParser() throws IOException {
DefaultDeserializationContext ctxt = createDeserializationContext();
return ctxt.assignAndReturnParser(_streamFactory.createNonBlockingByteArrayParser(ctxt));
}
/*
/**********************************************************************
/* Public API: constructing Generator that are properly linked
/* to `ObjectWriteContext`
/**********************************************************************
*/
/**
* Factory method for constructing {@link JsonGenerator} that is properly
* wired to allow callbacks for serialization: basically
* constructs a {@link ObjectWriteContext} and then calls
* {@link TokenStreamFactory#createGenerator(ObjectWriteContext,OutputStream)}.
*
* @since 3.0
*/
public JsonGenerator createGenerator(OutputStream out) throws IOException {
return _streamFactory.createGenerator(_serializerProvider(), out);
}
/**
* Factory method for constructing {@link JsonGenerator} that is properly
* wired to allow callbacks for serialization: basically
* constructs a {@link ObjectWriteContext} and then calls
* {@link TokenStreamFactory#createGenerator(ObjectWriteContext,OutputStream,JsonEncoding)}.
*
* @since 3.0
*/
public JsonGenerator createGenerator(OutputStream out, JsonEncoding enc) throws IOException {
return _streamFactory.createGenerator(_serializerProvider(), out, enc);
}
/**
* Factory method for constructing {@link JsonGenerator} that is properly
* wired to allow callbacks for serialization: basically
* constructs a {@link ObjectWriteContext} and then calls
* {@link TokenStreamFactory#createGenerator(ObjectWriteContext,Writer)}.
*
* @since 3.0
*/
public JsonGenerator createGenerator(Writer w) throws IOException {
return _streamFactory.createGenerator(_serializerProvider(), w);
}
/**
* Factory method for constructing {@link JsonGenerator} that is properly
* wired to allow callbacks for serialization: basically
* constructs a {@link ObjectWriteContext} and then calls
* {@link TokenStreamFactory#createGenerator(ObjectWriteContext,File,JsonEncoding)}.
*
* @since 3.0
*/
public JsonGenerator createGenerator(File f, JsonEncoding enc)
throws IOException {
return _streamFactory.createGenerator(_serializerProvider(), f, enc);
}
/**
* Factory method for constructing {@link JsonGenerator} that is properly
* wired to allow callbacks for serialization: basically
* constructs a {@link ObjectWriteContext} and then calls
* {@link TokenStreamFactory#createGenerator(ObjectWriteContext,DataOutput)}.
*
* @since 3.0
*/
public JsonGenerator createGenerator(DataOutput out) throws IOException {
return _streamFactory.createGenerator(_serializerProvider(), out);
}
/*
/**********************************************************************
/* Public API deserialization, main methods
/**********************************************************************
*/
/**
* Method to deserialize JSON content into a non-container
* type (it can be an array type, however): typically a bean, array
* or a wrapper type (like {@link java.lang.Boolean}).
*<p>
* Note: this method should NOT be used if the result type is a
* container ({@link java.util.Collection} or {@link java.util.Map}.
* The reason is that due to type erasure, key and value types
* cannot be introspected when using this method.
*
* @throws IOException if a low-level I/O problem (unexpected end-of-input,
* network error) occurs (passed through as-is without additional wrapping -- note
* that this is one case where {@link DeserializationFeature#WRAP_EXCEPTIONS}
* does NOT result in wrapping of exception even if enabled)
* @throws JsonParseException if underlying input contains invalid content
* of type {@link JsonParser} supports (JSON for default case)
* @throws JsonMappingException if the input JSON structure does not match structure
* expected for result type (or has other mismatch issues)
*/
@SuppressWarnings("unchecked")
public <T> T readValue(JsonParser p, Class<T> valueType)
throws IOException, JsonParseException, JsonMappingException
{
DeserializationContext ctxt = createDeserializationContext(p);
return (T) _readValue(ctxt, p, _typeFactory.constructType(valueType));
}
/**
* Method to deserialize JSON content into a Java type, reference
* to which is passed as argument. Type is passed using so-called
* "super type token" (see )
* and specifically needs to be used if the root type is a
* parameterized (generic) container type.
*
* @throws IOException if a low-level I/O problem (unexpected end-of-input,
* network error) occurs (passed through as-is without additional wrapping -- note
* that this is one case where {@link DeserializationFeature#WRAP_EXCEPTIONS}
* does NOT result in wrapping of exception even if enabled)
* @throws JsonParseException if underlying input contains invalid content
* of type {@link JsonParser} supports (JSON for default case)
* @throws JsonMappingException if the input JSON structure does not match structure
* expected for result type (or has other mismatch issues)
*/
@SuppressWarnings("unchecked")
public <T> T readValue(JsonParser p, TypeReference<T> valueTypeRef)
throws IOException, JsonParseException, JsonMappingException
{
DeserializationContext ctxt = createDeserializationContext(p);
return (T) _readValue(ctxt, p, _typeFactory.constructType(valueTypeRef));
}
/**
* Method to deserialize JSON content into a Java type, reference
* to which is passed as argument. Type is passed using
* Jackson specific type; instance of which can be constructed using
* {@link TypeFactory}.
*
* @throws IOException if a low-level I/O problem (unexpected end-of-input,
* network error) occurs (passed through as-is without additional wrapping -- note
* that this is one case where {@link DeserializationFeature#WRAP_EXCEPTIONS}
* does NOT result in wrapping of exception even if enabled)
* @throws JsonParseException if underlying input contains invalid content
* of type {@link JsonParser} supports (JSON for default case)
* @throws JsonMappingException if the input JSON structure does not match structure
* expected for result type (or has other mismatch issues)
*/
@SuppressWarnings("unchecked")
public final <T> T readValue(JsonParser p, ResolvedType valueType)
throws IOException, JsonParseException, JsonMappingException
{
DeserializationContext ctxt = createDeserializationContext(p);
return (T) _readValue(ctxt, p, (JavaType) valueType);
}
/**
* Type-safe overloaded method, basically alias for {@link #readValue(JsonParser, Class)}.
*
* @throws IOException if a low-level I/O problem (unexpected end-of-input,
* network error) occurs (passed through as-is without additional wrapping -- note
* that this is one case where {@link DeserializationFeature#WRAP_EXCEPTIONS}
* does NOT result in wrapping of exception even if enabled)
* @throws JsonParseException if underlying input contains invalid content
* of type {@link JsonParser} supports (JSON for default case)
* @throws JsonMappingException if the input JSON structure does not match structure
* expected for result type (or has other mismatch issues)
*/
@SuppressWarnings("unchecked")
public <T> T readValue(JsonParser p, JavaType valueType)
throws IOException, JsonParseException, JsonMappingException
{
DeserializationContext ctxt = createDeserializationContext(p);
return (T) _readValue(ctxt, p, valueType);
}
/**
* Method to deserialize JSON content as a tree {@link JsonNode}.
* Returns {@link JsonNode} that represents the root of the resulting tree, if there
* was content to read, or {@code null} if no more content is accessible
* via passed {@link JsonParser}.
*<p>
* NOTE! Behavior with end-of-input (no more content) differs between this
* {@code readTree} method, and all other methods that take input source: latter
* will return "missing node", NOT {@code null}
*
* @return a {@link JsonNode}, if valid JSON content found; null
* if input has no content to bind -- note, however, that if
* JSON <code>null</code> token is found, it will be represented
* as a non-null {@link JsonNode} (one that returns <code>true</code>
* for {@link JsonNode#isNull()}
*
* @throws IOException if a low-level I/O problem (unexpected end-of-input,
* network error) occurs (passed through as-is without additional wrapping -- note
* that this is one case where {@link DeserializationFeature#WRAP_EXCEPTIONS}
* does NOT result in wrapping of exception even if enabled)
* @throws JsonParseException if underlying input contains invalid content
* of type {@link JsonParser} supports (JSON for default case)
*/
public <T extends TreeNode> T readTree(JsonParser p)
throws IOException, JsonProcessingException
{
// Must check for EOF here before calling readValue(), since that'll choke on it otherwise
JsonToken t = p.currentToken();
if (t == null) {
t = p.nextToken();
if (t == null) {
return null;
}
}
DeserializationContext ctxt = createDeserializationContext(p);
// NOTE! _readValue() will check for trailing tokens
JsonNode n = (JsonNode) _readValue(ctxt, p, JSON_NODE_TYPE);
if (n == null) {
n = getNodeFactory().nullNode();
}
@SuppressWarnings("unchecked")
T result = (T) n;
return result;
}
/**
* Convenience method, equivalent in function to:
*<pre>
* readerFor(valueType).readValues(p);
*</pre>
*<p>
* Method for reading sequence of Objects from parser stream.
* Sequence can be either root-level "unwrapped" sequence (without surrounding
* JSON array), or a sequence contained in a JSON Array.
* In either case {@link JsonParser} <b>MUST</b> point to the first token of
* the first element, OR not point to any token (in which case it is advanced
* to the next token). This means, specifically, that for wrapped sequences,
* parser MUST NOT point to the surrounding <code>START_ARRAY</code> (one that
* contains values to read) but rather to the token following it which is the first
* token of the first value to read.
*<p>
* Note that {@link ObjectReader} has more complete set of variants.
*/
public <T> MappingIterator<T> readValues(JsonParser p, JavaType valueType)
throws IOException, JsonProcessingException
{
DeserializationContext ctxt = createDeserializationContext(p);
JsonDeserializer<?> deser = _findRootDeserializer(ctxt, valueType);
// false -> do NOT close JsonParser (since caller passed it)
return new MappingIterator<T>(valueType, p, ctxt, deser,
false, null);
}
/**
* Convenience method, equivalent in function to:
*<pre>
* readerFor(valueType).readValues(p);
*</pre>
*<p>
* Type-safe overload of {@link #readValues(JsonParser, JavaType)}.
*/
public <T> MappingIterator<T> readValues(JsonParser p, Class<T> valueType)
throws IOException, JsonProcessingException
{
return readValues(p, _typeFactory.constructType(valueType));
}
/*
/**********************************************************************
/* Public API: deserialization
/* (mapping from token stream to Java types)
/**********************************************************************
*/
/**
* Method to deserialize JSON content as tree expressed
* using set of {@link JsonNode} instances.
* Returns root of the resulting tree (where root can consist
* of just a single node if the current event is a
* value event, not container).
*<p>
* If a low-level I/O problem (missing input, network error) occurs,
* a {@link IOException} will be thrown.
* If a parsing problem occurs (invalid JSON),
* {@link JsonParseException} will be thrown.
* If no content is found from input (end-of-input), Java
* <code>null</code> will be returned.
*
* @param in Input stream used to read JSON content
* for building the JSON tree.
*
* @return a {@link JsonNode}, if valid JSON content found; null
* if input has no content to bind -- note, however, that if
* JSON <code>null</code> token is found, it will be represented
* as a non-null {@link JsonNode} (one that returns <code>true</code>
* for {@link JsonNode#isNull()}
*
* @throws JsonParseException if underlying input contains invalid content
* of type {@link JsonParser} supports (JSON for default case)
*/
public JsonNode readTree(InputStream in) throws IOException
{
DeserializationContext ctxt = createDeserializationContext();
return _readTreeAndClose(ctxt, _streamFactory.createParser(ctxt, in));
}
/**
* Same as {@link #readTree(InputStream)} except content accessed through
* passed-in {@link Reader}
*/
public JsonNode readTree(Reader r) throws IOException {
DeserializationContext ctxt = createDeserializationContext();
return _readTreeAndClose(ctxt, _streamFactory.createParser(ctxt, r));
}
/**
* Same as {@link #readTree(InputStream)} except content read from
* passed-in {@link String}
*/