-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathBeanSerializerBase.java
More file actions
1154 lines (1064 loc) · 46.9 KB
/
BeanSerializerBase.java
File metadata and controls
1154 lines (1064 loc) · 46.9 KB
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 tools.jackson.databind.ser.bean;
import java.util.*;
import com.fasterxml.jackson.annotation.*;
import tools.jackson.core.*;
import tools.jackson.core.type.WritableTypeId;
import tools.jackson.databind.*;
import tools.jackson.databind.introspect.AnnotatedMember;
import tools.jackson.databind.introspect.ObjectIdInfo;
import tools.jackson.databind.jsonFormatVisitors.JsonFormatVisitorWrapper;
import tools.jackson.databind.jsonFormatVisitors.JsonObjectFormatVisitor;
import tools.jackson.databind.jsontype.TypeSerializer;
import tools.jackson.databind.ser.*;
import tools.jackson.databind.ser.impl.ObjectIdWriter;
import tools.jackson.databind.ser.impl.PropertyBasedObjectIdGenerator;
import tools.jackson.databind.ser.jdk.EnumSerializer;
import tools.jackson.databind.ser.jdk.MapEntrySerializer;
import tools.jackson.databind.ser.std.StdContainerSerializer;
import tools.jackson.databind.ser.std.StdConvertingSerializer;
import tools.jackson.databind.ser.std.StdSerializer;
import tools.jackson.databind.util.ClassUtil;
import tools.jackson.databind.util.Converter;
import tools.jackson.databind.util.IgnorePropertiesUtil;
import tools.jackson.databind.util.NameTransformer;
/**
* Base class both for the standard bean serializer, and couple
* of variants that only differ in small details.
* Can be used for custom bean serializers as well, although that
* is not the primary design goal.
*/
public abstract class BeanSerializerBase
extends StdSerializer<Object>
{
protected final static PropertyName NAME_FOR_OBJECT_REF = new PropertyName("#object-ref");
final protected static BeanPropertyWriter[] NO_PROPS = new BeanPropertyWriter[0];
/*
/**********************************************************************
/* Configuration
/**********************************************************************
*/
final protected JavaType _beanType;
/**
* Writers used for outputting actual property values
*/
final protected BeanPropertyWriter[] _props;
/**
* Optional filters used to suppress output of properties that
* are only to be included in certain views
*/
final protected BeanPropertyWriter[] _filteredProps;
/**
* Id of the bean property filter to use, if any; null if none.
*/
final protected Object _propertyFilterId;
/**
* If using custom type ids (usually via getter, or field), this is the
* reference to that member.
*/
final protected AnnotatedMember _typeId;
/**
* If this POJO can be alternatively serialized using just an object id
* to denote a reference to previously serialized object,
* this Object will handle details.
*/
final protected ObjectIdWriter _objectIdWriter;
/**
* Requested shape from bean class annotations.
*/
final protected JsonFormat.Shape _serializationShape;
/**
* Name of a bean property whose serialized name equals the
* {@code EXTERNAL_PROPERTY} type id name of this type's polymorphic
* {@link TypeSerializer}, if any. Computed in {@link #resolve}. When
* non-null, {@link #serializeWithType} suppresses the otherwise-emitted
* duplicate type id key so the bean's own property wins ([databind#2844]).
*/
protected String _externalTypeIdToSuppress;
/*
/**********************************************************************
/* Life-cycle: constructors
/**********************************************************************
*/
/**
* Constructor used by {@link BeanSerializerBuilder} to create an
* instance
*
* @param type Nominal type of values handled by this serializer
* @param builder Builder for accessing other collected information
*/
protected BeanSerializerBase(JavaType type, BeanSerializerBuilder builder,
BeanPropertyWriter[] properties, BeanPropertyWriter[] filteredProperties)
{
super(type);
_beanType = type;
_props = properties;
_filteredProps = filteredProperties;
if (builder == null) { // mostly for testing
// 20-Sep-2019, tatu: Actually not just that but also "dummy" serializer for
// case of no bean properties, too
_typeId = null;
_propertyFilterId = null;
_objectIdWriter = null;
_serializationShape = null;
} else {
_typeId = builder.getTypeId();
_propertyFilterId = builder.getFilterId();
_objectIdWriter = builder.getObjectIdWriter();
JsonFormat.Value format = builder.getBeanDescriptionRef()
.findExpectedFormat(type.getRawClass());
_serializationShape = format.getShape();
}
}
/**
* Copy-constructor that is useful for sub-classes that just want to
* copy all super-class properties without modifications.
*/
protected BeanSerializerBase(BeanSerializerBase src) {
this(src, src._props, src._filteredProps);
}
protected BeanSerializerBase(BeanSerializerBase src,
BeanPropertyWriter[] properties, BeanPropertyWriter[] filteredProperties)
{
super(src._handledType);
_beanType = src._beanType;
_props = properties;
_filteredProps = filteredProperties;
_typeId = src._typeId;
_objectIdWriter = src._objectIdWriter;
_propertyFilterId = src._propertyFilterId;
_serializationShape = src._serializationShape;
_externalTypeIdToSuppress = src._externalTypeIdToSuppress;
}
protected BeanSerializerBase(BeanSerializerBase src,
ObjectIdWriter objectIdWriter)
{
this(src, objectIdWriter, src._propertyFilterId);
}
protected BeanSerializerBase(BeanSerializerBase src,
ObjectIdWriter objectIdWriter, Object filterId)
{
super(src._handledType);
_beanType = src._beanType;
_props = src._props;
_filteredProps = src._filteredProps;
_typeId = src._typeId;
_objectIdWriter = objectIdWriter;
_propertyFilterId = filterId;
_serializationShape = src._serializationShape;
_externalTypeIdToSuppress = src._externalTypeIdToSuppress;
}
protected BeanSerializerBase(BeanSerializerBase src, Set<String> toIgnore, Set<String> toInclude)
{
super(src._handledType);
_beanType = src._beanType;
final BeanPropertyWriter[] propsIn = src._props;
final BeanPropertyWriter[] fpropsIn = src._filteredProps;
final int len = propsIn.length;
ArrayList<BeanPropertyWriter> propsOut = new ArrayList<BeanPropertyWriter>(len);
ArrayList<BeanPropertyWriter> fpropsOut = (fpropsIn == null) ? null : new ArrayList<BeanPropertyWriter>(len);
for (int i = 0; i < len; ++i) {
BeanPropertyWriter bpw = propsIn[i];
// should be ignored?
if (IgnorePropertiesUtil.shouldIgnore(bpw.getName(), toIgnore, toInclude)) {
continue;
}
propsOut.add(bpw);
if (fpropsIn != null) {
fpropsOut.add(fpropsIn[i]);
}
}
_props = propsOut.toArray(NO_PROPS);
_filteredProps = (fpropsOut == null) ? null : fpropsOut.toArray(NO_PROPS);
_typeId = src._typeId;
_objectIdWriter = src._objectIdWriter;
_propertyFilterId = src._propertyFilterId;
_serializationShape = src._serializationShape;
// If the removed property was the one that triggered suppression, drop
// the flag so the type id is once again emitted.
String suppressName = src._externalTypeIdToSuppress;
if (suppressName != null) {
boolean stillPresent = false;
for (BeanPropertyWriter w : _props) {
if (suppressName.equals(w.getName())) {
stillPresent = true;
break;
}
}
if (!stillPresent) {
suppressName = null;
}
}
_externalTypeIdToSuppress = suppressName;
}
/**
* Mutant factory used for creating a new instance with different
* {@link ObjectIdWriter}.
*/
public abstract BeanSerializerBase withObjectIdWriter(ObjectIdWriter objectIdWriter);
/**
* Mutant factory used for creating a new instance with additional
* set of properties to ignore or include (from properties this instance otherwise has)
*/
protected abstract BeanSerializerBase withByNameInclusion(Set<String> toIgnore,
Set<String> toInclude);
/**
* Mutant factory for creating a variant that output POJO as a
* JSON Array. Implementations may ignore this request if output
* as array is not possible (either at all, or reliably).
*/
protected abstract BeanSerializerBase asArraySerializer();
/**
* Mutant factory used for creating a new instance with different
* filter id (used with <code>JsonFilter</code> annotation)
*/
@Override
public abstract BeanSerializerBase withFilterId(Object filterId);
/**
* Mutant factory used for creating a new instance with modified set
* of properties
*/
protected abstract BeanSerializerBase withProperties(BeanPropertyWriter[] properties,
BeanPropertyWriter[] filteredProperties);
/**
* Lets force sub-classes to implement this, to avoid accidental missing
* of handling...
*/
@Override
public abstract ValueSerializer<Object> unwrappingSerializer(NameTransformer unwrapper);
/**
* Copy-constructor that will also rename properties with given prefix
* (if it's non-empty)
*/
protected BeanSerializerBase(BeanSerializerBase src, NameTransformer unwrapper) {
this(src, rename(src._props, unwrapper), rename(src._filteredProps, unwrapper));
}
private final static BeanPropertyWriter[] rename(BeanPropertyWriter[] props,
NameTransformer transformer)
{
if (props == null || props.length == 0 || transformer == null || transformer == NameTransformer.NOP) {
return props;
}
final int len = props.length;
BeanPropertyWriter[] result = new BeanPropertyWriter[len];
for (int i = 0; i < len; ++i) {
BeanPropertyWriter bpw = props[i];
if (bpw != null) {
result[i] = bpw.rename(transformer);
}
}
return result;
}
/*
/**********************************************************************
/* Post-construction processing: resolvable, contextual
/**********************************************************************
*/
/**
* We need to resolve dependant serializers here
* to be able to properly handle cyclic type references.
*/
@Override
public void resolve(SerializationContext ctxt)
{
int filteredCount = (_filteredProps == null) ? 0 : _filteredProps.length;
for (int i = 0, len = _props.length; i < len; ++i) {
BeanPropertyWriter prop = _props[i];
// let's start with null serializer resolution actually
if (!prop.willSuppressNulls() && !prop.hasNullSerializer()) {
ValueSerializer<Object> nullSer = ctxt.findNullValueSerializer(prop);
if (nullSer != null) {
prop.assignNullSerializer(nullSer);
// also: remember to replace filtered property too?
if (i < filteredCount) {
BeanPropertyWriter w2 = _filteredProps[i];
if (w2 != null) {
w2.assignNullSerializer(nullSer);
}
}
}
}
if (prop.hasSerializer()) {
continue;
}
// [databind#124]: allow use of converters
ValueSerializer<Object> ser = findConvertingSerializer(ctxt, prop);
if (ser == null) {
// Was the serialization type hard-coded? If so, use it
JavaType type = prop.getSerializationType();
// It not, we can use declared return type if and only if declared type is final:
// if not, we don't really know the actual type until we get the instance.
if (type == null) {
type = prop.getType();
// [databind#5615]: _nonTrivialBaseType now set in BeanPropertyWriter
// constructor to avoid race condition
if (!type.isFinal()) {
continue;
}
}
ser = ctxt.findPrimaryPropertySerializer(type, prop);
// 04-Feb-2010, tatu: We may have stashed type serializer for content types
// too, earlier; if so, it's time to connect the dots here:
if (type.isContainerType()) {
TypeSerializer typeSer = (TypeSerializer) type.getContentType().getTypeHandler();
if (typeSer != null) {
// for now, can do this only for standard containers...
if (ser instanceof StdContainerSerializer<?>) {
// ugly casts... but necessary
@SuppressWarnings("unchecked")
ValueSerializer<Object> ser2 = (ValueSerializer<Object>)((StdContainerSerializer<?>) ser).withValueTypeSerializer(typeSer);
ser = ser2;
}
}
}
}
// and maybe replace filtered property too?
if (i < filteredCount) {
BeanPropertyWriter w2 = _filteredProps[i];
if (w2 != null) {
w2.assignSerializer(ser);
// 17-Mar-2017, tatu: Typically will lead to chained call to original property,
// which would lead to double set. Not a problem itself, except... unwrapping
// may require work to be done, which does lead to an actual issue.
continue;
}
}
prop.assignSerializer(ser);
}
// also, any-getter may need to be resolved
for (int i = 0; i < _props.length; i++) {
BeanPropertyWriter prop = _props[i];
if (prop instanceof AnyGetterWriter anyGetterWriter) {
anyGetterWriter.resolve(ctxt);
}
}
// [databind#2883]: now that inner serializers (and their post-transformation
// property names) are known, verify no unwrapped property clashes with any
// other property
_verifyNoUnwrappedPropertyConflict(ctxt);
// [databind#2844]: if this type's polymorphic TypeSerializer would emit
// a type id under a property name that collides with one of our bean
// properties, remember that name so serializeWithType can suppress the
// duplicate key emission and let the bean's own property value win.
_externalTypeIdToSuppress = _findExternalTypeIdPropertyToSuppress(ctxt);
}
private String _findExternalTypeIdPropertyToSuppress(SerializationContext ctxt)
{
// Read the annotation directly rather than resolving a TypeSerializer:
// findTypeSerializer would construct a fresh TypeSerializer instance and
// call init() on any custom TypeIdResolver, which is a visible side
// effect some tests (and users) rely on being invoked exactly once.
final AnnotationIntrospector intr = ctxt.getAnnotationIntrospector();
if (intr == null) {
return null;
}
JsonTypeInfo.Value typeInfo = intr.findPolymorphicTypeInfo(ctxt.getConfig(),
ctxt.introspectClassAnnotations(_beanType));
if (typeInfo == null) {
return null;
}
// Class-level EXTERNAL_PROPERTY is rewritten to PROPERTY by
// TypeResolverProvider (external-id only makes sense on a containing
// property). Either value collides with a same-named bean property.
JsonTypeInfo.As incl = typeInfo.getInclusionType();
if (incl != JsonTypeInfo.As.PROPERTY
&& incl != JsonTypeInfo.As.EXTERNAL_PROPERTY) {
return null;
}
String name = typeInfo.getPropertyName();
if (name == null || name.isEmpty()) {
return null;
}
for (BeanPropertyWriter w : _props) {
if (name.equals(w.getName())) {
return name;
}
}
return null;
}
/**
* Called at end of {@link #resolve} to verify that no property produced by an
* unwrapped ({@code @JsonUnwrapped}) property collides with a regular property
* (or with an earlier unwrapped property) by name.
*<p>
* Relies on inner unwrapping serializers having been assigned by
* {@link UnwrappingBeanPropertyWriter#assignSerializer}, so that their
* already-renamed {@code _props} can be consulted directly; this avoids
* re-introspecting the unwrapped type and re-applying name transformations.
*
* @since 3.2
*/
protected void _verifyNoUnwrappedPropertyConflict(SerializationContext ctxt)
{
// Fast-path: no unwrapped properties, nothing to check
boolean anyUnwrapped = false;
for (BeanPropertyWriter p : _props) {
if (p instanceof UnwrappingBeanPropertyWriter) {
anyUnwrapped = true;
break;
}
}
if (!anyUnwrapped) {
return;
}
// seenNames grows as we go so a later unwrapped property's names are
// also checked against earlier unwrapped properties'.
final Set<String> seenNames = new HashSet<>(_props.length);
for (BeanPropertyWriter p : _props) {
// Skip unwrapped props here (handled below); also skip AnyGetterWriter,
// since its emitted property names come from runtime map keys rather
// than from its own getName().
if (p instanceof UnwrappingBeanPropertyWriter || p instanceof AnyGetterWriter) {
continue;
}
seenNames.add(p.getName());
}
for (BeanPropertyWriter p : _props) {
if (!(p instanceof UnwrappingBeanPropertyWriter unwrapped)) {
continue;
}
// Skip self-referential unwrap to avoid spurious self-conflicts
// and potential infinite recursion while resolving the inner
// serializer. Self-referential @JsonUnwrapped is structurally
// broken (would infinite-loop on any non-null value) but nothing
// here enforces that; runtime will error out if exercised.
if (unwrapped.getType().getRawClass() == _beanType.getRawClass()) {
continue;
}
// Inner serializer may be a custom (non-BeanSerializerBase) impl;
// without access to its effective property names we cannot check it.
if (!(unwrapped.findUnwrappingSerializer(ctxt) instanceof BeanSerializerBase innerSer)) {
continue;
}
for (Iterator<PropertyWriter> it = innerSer.properties(); it.hasNext(); ) {
PropertyWriter innerProp = it.next();
// Skip nested UnwrappingBeanPropertyWriters: their own `getName()` is
// the Java field name of a further unwrapped property, which is NOT
// what gets emitted (its contents are unwrapped at that level). Means
// conflicts across more than one level of nesting aren't detected, but
// false positives are avoided.
if (innerProp instanceof UnwrappingBeanPropertyWriter) {
continue;
}
String name = innerProp.getName();
if (!seenNames.add(name)) {
ctxt.reportBadDefinition(_beanType, String.format(
"Conflict between unwrapped property '%s' (of type %s)"
+" and another property with same name;"
+" consider using `@JsonUnwrapped(prefix=...)` to avoid name collision",
name, ClassUtil.getTypeDescription(unwrapped.getType())));
}
}
}
}
/**
* Helper method that can be used to see if specified property is annotated
* to indicate use of a converter for property value (in case of container types,
* it is container type itself, not key or content type).
*/
protected ValueSerializer<Object> findConvertingSerializer(SerializationContext ctxt,
BeanPropertyWriter prop)
{
final AnnotationIntrospector intr = ctxt.getAnnotationIntrospector();
if (intr != null) {
AnnotatedMember m = prop.getMember();
if (m != null) {
Object convDef = intr.findSerializationConverter(ctxt.getConfig(), m);
if (convDef != null) {
Converter<Object,Object> conv = ctxt.converterInstance(prop.getMember(), convDef);
JavaType delegateType = conv.getOutputType(ctxt.getTypeFactory());
// [databind#731]: Should skip if nominally java.lang.Object
ValueSerializer<?> ser = delegateType.isJavaLangObject() ? null
: ctxt.findPrimaryPropertySerializer(delegateType, prop);
return new StdConvertingSerializer(conv, delegateType, ser, prop);
}
}
}
return null;
}
@SuppressWarnings("incomplete-switch")
@Override
public ValueSerializer<?> createContextual(SerializationContext ctxt, BeanProperty property)
{
final AnnotationIntrospector intr = ctxt.getAnnotationIntrospector();
final AnnotatedMember accessor = _neitherNull(property, intr)
? property.getMember() : null;
final SerializationConfig config = ctxt.getConfig();
// Let's start with one big transmutation: Enums that are annotated
// to serialize as Objects may want to revert
JsonFormat.Value format = findFormatOverrides(ctxt, property, _handledType);
JsonFormat.Shape shape = null;
if ((format != null) && format.hasShape()) {
shape = format.getShape();
// or, alternatively, asked to revert "back to" other representations...
if ((shape != JsonFormat.Shape.ANY) && (shape != _serializationShape)) {
if (_beanType.isEnumType()) {
switch (shape) {
case STRING:
case NUMBER:
case NUMBER_INT:
// 12-Oct-2014, tatu: May need to introspect full annotations... but
// for now, just do class ones
BeanDescription desc = ctxt.introspectBeanDescription(_beanType);
ValueSerializer<?> ser = EnumSerializer.construct(_beanType.getRawClass(),
config, desc, format);
return ctxt.handlePrimaryContextualization(ser, property);
}
// 16-Oct-2016, tatu: Ditto for `Map`, `Map.Entry` subtypes
} else if (shape == JsonFormat.Shape.NATURAL) {
if (_beanType.isMapLikeType() && Map.class.isAssignableFrom(_handledType)) {
;
} else if (Map.Entry.class.isAssignableFrom(_handledType)) {
JavaType mapEntryType = _beanType.findSuperType(Map.Entry.class);
JavaType kt = mapEntryType.containedTypeOrUnknown(0);
JavaType vt = mapEntryType.containedTypeOrUnknown(1);
// 16-Oct-2016, tatu: could have problems with type handling, as we do not
// see if "static" typing is needed, nor look for `TypeSerializer` yet...
ValueSerializer<?> ser = new MapEntrySerializer(_beanType, kt, vt,
false, null, property);
return ctxt.handlePrimaryContextualization(ser, property);
}
}
}
}
ObjectIdWriter oiw = _objectIdWriter;
// 16-Jun-2020, tatu: [databind#2759] means we need to handle reordering
// at a later point
int idPropOrigIndex = 0;
Set<String> ignoredProps = null;
Set<String> includedProps = null;
Object newFilterId = null;
// Then we may have an override for Object Id
if (accessor != null) {
ignoredProps = intr.findPropertyIgnoralByName(config, accessor).findIgnoredForSerialization();
includedProps = intr.findPropertyInclusionByName(config, accessor).getIncluded();
ObjectIdInfo objectIdInfo = intr.findObjectIdInfo(config, accessor);
if (objectIdInfo == null) {
// no ObjectId override, but maybe ObjectIdRef?
if (oiw != null) {
objectIdInfo = intr.findObjectReferenceInfo(config, accessor, null);
if (objectIdInfo != null) {
oiw = _objectIdWriter.withAlwaysAsId(objectIdInfo.getAlwaysAsId());
}
}
} else {
// Ugh: mostly copied from BeanDeserializerBase: but can't easily change it
// to be able to move to SerializationContext (where it really belongs)
// 2.1: allow modifications by "id ref" annotations as well:
objectIdInfo = intr.findObjectReferenceInfo(config, accessor, objectIdInfo);
Class<?> implClass = objectIdInfo.getGeneratorType();
JavaType type = ctxt.constructType(implClass);
JavaType idType = ctxt.getTypeFactory().findTypeParameters(type, ObjectIdGenerator.class)[0];
// Property-based generator is trickier
if (implClass == ObjectIdGenerators.PropertyGenerator.class) { // most special one, needs extra work
String propName = objectIdInfo.getPropertyName().getSimpleName();
BeanPropertyWriter idProp = null;
for (int i = 0, len = _props.length; ; ++i) {
if (i == len) {
ctxt.reportBadDefinition(_beanType, String.format(
"Invalid Object Id definition for %s: cannot find property with name %s",
ClassUtil.getTypeDescription(_beanType), ClassUtil.name(propName)));
}
BeanPropertyWriter prop = _props[i];
if (propName.equals(prop.getName())) {
idProp = prop;
// Let's mark id prop to be moved as the first (may still get rearranged)
// (although it may still get rearranged etc)
idPropOrigIndex = i;
break;
}
}
idType = idProp.getType();
ObjectIdGenerator<?> gen = new PropertyBasedObjectIdGenerator(objectIdInfo, idProp);
oiw = ObjectIdWriter.construct(idType, (PropertyName) null, gen, objectIdInfo.getAlwaysAsId());
} else { // other types need to be simpler
ObjectIdGenerator<?>gen = ctxt.objectIdGeneratorInstance(accessor, objectIdInfo);
oiw = ObjectIdWriter.construct(idType, objectIdInfo.getPropertyName(), gen,
objectIdInfo.getAlwaysAsId());
}
}
// Or change Filter Id in use?
Object filterId = intr.findFilterId(config, accessor);
// but only consider case of adding a new filter id (no removal via annotation)
if (filterId != null && !filterId.equals(_propertyFilterId)) {
newFilterId = filterId;
}
}
// either way, need to resolve serializer:
BeanSerializerBase contextual = this;
// 16-Jun-2020, tatu: [databind#2759] must make copies, then reorder
if (idPropOrigIndex > 0) { // note: must shuffle both regular properties and filtered
final BeanPropertyWriter[] newProps = Arrays.copyOf(_props, _props.length);
BeanPropertyWriter bpw = newProps[idPropOrigIndex];
System.arraycopy(newProps, 0, newProps, 1, idPropOrigIndex);
newProps[0] = bpw;
final BeanPropertyWriter[] newFiltered;
if (_filteredProps == null) {
newFiltered = null;
} else {
newFiltered = Arrays.copyOf(_filteredProps, _filteredProps.length);
bpw = newFiltered[idPropOrigIndex];
System.arraycopy(newFiltered, 0, newFiltered, 1, idPropOrigIndex);
newFiltered[0] = bpw;
}
contextual = contextual.withProperties(newProps, newFiltered);
}
if (oiw != null) {
// not really associated with the property so let's not pass it?
ValueSerializer<?> ser = ctxt.findRootValueSerializer(oiw.idType);
oiw = oiw.withSerializer(ser);
if (oiw != _objectIdWriter) {
contextual = contextual.withObjectIdWriter(oiw);
}
}
// Possibly change inclusions: for ignored, only non-empty set matters;
// for inclusion `null` means "not defined" but empty "include nothing":
if (((ignoredProps != null) && !ignoredProps.isEmpty())
|| (includedProps != null)) {
contextual = contextual.withByNameInclusion(ignoredProps, includedProps);
}
if (newFilterId != null) {
contextual = contextual.withFilterId(newFilterId);
}
if (shape == null) {
shape = _serializationShape;
}
// last but not least; may need to transmute into as-array serialization
if (shape == JsonFormat.Shape.ARRAY) {
return contextual.asArraySerializer();
}
return contextual;
}
/*
/**********************************************************************
/* Public accessors
/**********************************************************************
*/
@Override
public Iterator<PropertyWriter> properties() {
return Arrays.<PropertyWriter>asList(_props).iterator();
}
/**
* @since 3.0
*/
public int propertyCount() {
return _props.length;
}
/**
* Accessor for checking if view-processing is enabled for this bean,
* that is, if it has separate set of properties with view-checking
* added.
*
* @since 3.0
*/
public boolean hasViewProperties() {
return (_filteredProps != null);
}
/**
* @since 3.0
*/
public Object getFilterId() {
return _propertyFilterId;
}
/*
/**********************************************************************
/* Helper methods for implementation classes
/**********************************************************************
*/
/**
* Helper method for sub-classes to check if it should be possible to
* construct an "as-array" serializer. Returns if all of following
* hold true:
*<ul>
* <li>have Object Id (may be allowed in future)</li>
* <li>have "any getter"</li>
* </ul>
*
* @since 3.0
*/
public boolean canCreateArraySerializer() {
return (_objectIdWriter == null)
// 08-Feb-2025, tatu: [databind#4775] any-getter is fine now
//&& (_anyGetterWriter == null)
;
}
/*
/**********************************************************************
/* Partial ValueSerializer implementation
/**********************************************************************
*/
@Override
public boolean usesObjectId() {
return (_objectIdWriter != null);
}
// Main serialization method left unimplemented
@Override
public abstract void serialize(Object bean, JsonGenerator gen, SerializationContext ctxt)
throws JacksonException;
// Type-info-augmented case implemented as it does not usually differ between impls
@Override
public void serializeWithType(Object bean,
JsonGenerator gen, SerializationContext ctxt, TypeSerializer typeSer)
throws JacksonException
{
if (_objectIdWriter != null) {
_serializeWithObjectId(bean, gen, ctxt, typeSer);
return;
}
// [databind#2844]: when this bean has a property whose serialized name
// equals the type id property name and the type id would be emitted as
// a JSON property (PROPERTY / EXTERNAL_PROPERTY inclusion on a
// non-native-type-id format), suppress the type id so the bean's own
// property wins instead of producing a duplicate key. Binary formats
// with native type id support (canWriteTypeId()) don't have a
// collision, so we leave them alone.
if (_shouldSuppressTypeIdForDuplicateProperty(gen, typeSer)) {
gen.writeStartObject(bean);
gen.assignCurrentValue(bean);
if (_propertyFilterId != null) {
_serializePropertiesFiltered(bean, gen, ctxt, _propertyFilterId);
} else {
_serializeProperties(bean, gen, ctxt);
}
gen.writeEndObject();
return;
}
WritableTypeId typeIdDef = _typeIdDef(typeSer, bean, JsonToken.START_OBJECT);
typeSer.writeTypePrefix(gen, ctxt, typeIdDef);
gen.assignCurrentValue(bean); // [databind#631]
if (_propertyFilterId != null) {
_serializePropertiesFiltered(bean, gen, ctxt, _propertyFilterId);
} else {
_serializeProperties(bean, gen, ctxt);
}
typeSer.writeTypeSuffix(gen, ctxt, typeIdDef);
}
private boolean _shouldSuppressTypeIdForDuplicateProperty(JsonGenerator gen,
TypeSerializer typeSer)
{
if (_externalTypeIdToSuppress == null
|| !_externalTypeIdToSuppress.equals(typeSer.getPropertyName())) {
return false;
}
JsonTypeInfo.As incl = typeSer.getTypeInclusion();
if (incl != JsonTypeInfo.As.PROPERTY && incl != JsonTypeInfo.As.EXTERNAL_PROPERTY) {
return false;
}
// Native type id formats encode the type id outside the JSON property
// space, so no key collision can occur.
return !gen.canWriteTypeId();
}
protected final void _serializeWithObjectId(Object bean, JsonGenerator g,
SerializationContext ctxt, boolean startEndObject)
throws JacksonException
{
final ObjectIdWriter w = _objectIdWriter;
WritableObjectId objectId = ctxt.findObjectId(bean, w.generator);
// If possible, write as id already
if (objectId.writeAsReference(g, ctxt, w)) {
return;
}
// If not, need to inject the id:
Object id = objectId.generateId(bean);
if (w.alwaysAsId) {
w.serializer.serialize(id, g, ctxt);
return;
}
if (startEndObject) {
g.writeStartObject(bean);
}
objectId.writeAsDeclaration(g, ctxt, w);
if (_propertyFilterId != null) {
_serializePropertiesFiltered(bean, g, ctxt, _propertyFilterId);
} else {
_serializeProperties(bean, g, ctxt);
}
if (startEndObject) {
g.writeEndObject();
}
}
protected final void _serializeWithObjectId(Object bean, JsonGenerator g, SerializationContext ctxt,
TypeSerializer typeSer)
throws JacksonException
{
g.assignCurrentValue(bean);
final ObjectIdWriter w = _objectIdWriter;
WritableObjectId objectId = ctxt.findObjectId(bean, w.generator);
// If possible, write as id already; but unlike non-typed case, may need to
// wrap with type information for proper deserialization [databind#2780]
if (objectId.canWriteAsReference(g, ctxt, w)) {
// [databind#5851]: Only wrap with type info for wrapping inclusion styles
// (WRAPPER_ARRAY, WRAPPER_OBJECT). For PROPERTY/EXISTING_PROPERTY/EXTERNAL_PROPERTY
// styles, the type context is already established by the property and wrapping
// a scalar id reference would produce unexpected output (e.g. array wrapper fallback).
final JsonTypeInfo.As inclusion = typeSer.getTypeInclusion();
if (inclusion == JsonTypeInfo.As.WRAPPER_ARRAY
|| inclusion == JsonTypeInfo.As.WRAPPER_OBJECT) {
WritableTypeId typeIdDef = _typeIdDef(typeSer, bean, JsonToken.VALUE_NUMBER_INT);
typeSer.writeTypePrefix(g, ctxt, typeIdDef);
objectId.writeAsReference(g, ctxt, w);
typeSer.writeTypeSuffix(g, ctxt, typeIdDef);
} else {
objectId.writeAsReference(g, ctxt, w);
}
return;
}
// If not, need to inject the id:
Object id = objectId.generateId(bean);
if (w.alwaysAsId) {
w.serializer.serialize(id, g, ctxt);
return;
}
_serializeObjectId(bean, g, ctxt, typeSer, objectId);
}
protected void _serializeObjectId(Object bean,
JsonGenerator g, SerializationContext ctxt,
TypeSerializer typeSer, WritableObjectId objectId)
throws JacksonException
{
final ObjectIdWriter w = _objectIdWriter;
WritableTypeId typeIdDef = _typeIdDef(typeSer, bean, JsonToken.START_OBJECT);
typeSer.writeTypePrefix(g, ctxt, typeIdDef);
objectId.writeAsDeclaration(g, ctxt, w);
if (_propertyFilterId != null) {
_serializePropertiesFiltered(bean, g, ctxt, _propertyFilterId);
} else {
_serializeProperties(bean, g, ctxt);
}
typeSer.writeTypeSuffix(g, ctxt, typeIdDef);
}
protected final WritableTypeId _typeIdDef(TypeSerializer typeSer,
Object bean, JsonToken valueShape) {
if (_typeId == null) {
return typeSer.typeId(bean, valueShape);
}
Object typeId = _typeId.getValue(bean);
if (typeId == null) {
// 28-Jun-2017, tatu: Is this really needed? Unchanged from 2.8 but...
typeId = "";
}
return typeSer.typeId(bean, valueShape, typeId);
}
/*
/**********************************************************************
/* Field serialization methods, 3.0
/**********************************************************************
*/
/**
* Method called when neither JSON Filter is to be applied, nor
* view-filtering. This means that all property writers are non null
* and can be called directly.
*
* @since 3.0
*/
protected void _serializePropertiesNoView(Object bean, JsonGenerator gen,
SerializationContext ctxt, BeanPropertyWriter[] props)
throws JacksonException
{
int i = 0;
int left = props.length;
BeanPropertyWriter prop = null;
try {
if (left > 3) {
do {
prop = props[i];
prop.serializeAsProperty(bean, gen, ctxt);
prop = props[i+1];
prop.serializeAsProperty(bean, gen, ctxt);
prop = props[i+2];
prop.serializeAsProperty(bean, gen, ctxt);
prop = props[i+3];
prop.serializeAsProperty(bean, gen, ctxt);
left -= 4;
i += 4;
} while (left > 3);
}
switch (left) {
case 3:
prop = props[i++];
prop.serializeAsProperty(bean, gen, ctxt);
case 2:
prop = props[i++];
prop.serializeAsProperty(bean, gen, ctxt);
case 1:
prop = props[i++];
prop.serializeAsProperty(bean, gen, ctxt);
}
} catch (Exception e) {
// 08-Feb-2025, tatu: !!! As per [databind#4775] should no longer need
// special handling for any-setter here, right?
String name = (prop == null) ? "[anySetter]" : prop.getName();
wrapAndThrow(ctxt, e, bean, name);
} catch (StackOverflowError e) {
final String name = (prop == null) ? "[anySetter]" : prop.getName();
throw DatabindException.from(gen, "Infinite recursion (StackOverflowError)", e)
.prependPath(bean, name);
}
}
/**
* Method called when no JSON Filter is to be applied, but
* View filtering is in effect and so some of properties may be
* nulls to check.
*
* @since 3.0
*/
protected void _serializePropertiesMaybeView(Object bean, JsonGenerator g,
SerializationContext ctxt, BeanPropertyWriter[] props)
throws JacksonException
{
int i = 0;
int left = props.length;
BeanPropertyWriter prop = null;
try {
if (left > 3) {
do {
prop = props[i];
if (prop != null) {
prop.serializeAsProperty(bean, g, ctxt);
}
prop = props[i+1];