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 { 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; /* /********************************************************************** /* 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; } 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; } protected BeanSerializerBase(BeanSerializerBase src, Set toIgnore, Set toInclude) { super(src._handledType); _beanType = src._beanType; final BeanPropertyWriter[] propsIn = src._props; final BeanPropertyWriter[] fpropsIn = src._filteredProps; final int len = propsIn.length; ArrayList propsOut = new ArrayList(len); ArrayList fpropsOut = (fpropsIn == null) ? null : new ArrayList(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; } /** * 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 toIgnore, Set 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 JsonFilter 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 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; } // Helper for [databind#2759] / [databind#6410]: copy with Object Id property moved // first; and as plain (not View-filtered) writer private static BeanPropertyWriter[] _withIdPropFirst(BeanPropertyWriter[] props, int idIndex, BeanPropertyWriter idProp) { final BeanPropertyWriter[] result = Arrays.copyOf(props, props.length); System.arraycopy(result, 0, result, 1, idIndex); result[0] = idProp; 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 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 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 serializer) { // ugly casts... but necessary @SuppressWarnings("unchecked") ValueSerializer ser2 = (ValueSerializer)serializer.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); } /** * 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. *

* 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 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. // Follow any delegatee chain first, so that delegating serializers -- // notably `StdConvertingSerializer` produced by `@JsonSerialize(converter=)`, // see [databind#6017] -- are seen through to the underlying bean serializer. BeanSerializerBase innerSer = _asBeanSerializer(unwrapped.findUnwrappingSerializer(ctxt)); if (innerSer == null) { continue; } for (Iterator 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 for type %s: unwrapped property '%s' (of type %s)" +" and another property have the same name;" +" consider using `@JsonUnwrapped(prefix=...)` to avoid name collision", ClassUtil.getTypeDescription(_beanType), name, ClassUtil.getTypeDescription(unwrapped.getType()))); } } } } /** * Helper for {@link #_verifyNoUnwrappedPropertyConflict}: follows the * {@link ValueSerializer#getDelegatee()} chain -- used by delegating serializers * such as {@code StdConvertingSerializer} for {@code @JsonSerialize(converter=)}, * see [databind#6017] -- down to the underlying {@link BeanSerializerBase}, if any. * * @return Underlying bean serializer, or {@code null} if none found * * @since 3.2 */ protected static BeanSerializerBase _asBeanSerializer(ValueSerializer ser) { // Fixed depth bound to avoid spinning on a pathological delegatee chain for (int i = 0; (ser != null) && (i < 100); ++i) { if (ser instanceof BeanSerializerBase bs) { return bs; } ser = ser.getDelegatee(); } return null; } /** * 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 findConvertingSerializer(SerializationContext ctxt, BeanPropertyWriter prop) { AnnotatedMember m = prop.getMember(); if (m != null) { Object convDef = ctxt.getAnnotationIntrospector() .findSerializationConverter(ctxt.getConfig(), m); if (convDef != null) { Converter 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 = (property == null) ? null : property.getMember(); 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 = -1; Set ignoredProps = null; Set 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 ObjectIdGeneratorgen = 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 // [databind#6410]: and Object Id property must not be filtered by View if (idPropOrigIndex >= 0) { // note: must shuffle both regular properties and filtered final BeanPropertyWriter idProp = _props[idPropOrigIndex]; contextual = contextual.withProperties( _withIdPropFirst(_props, idPropOrigIndex, idProp), (_filteredProps == null) ? null : _withIdPropFirst(_filteredProps, idPropOrigIndex, idProp)); } 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) { if (contextual.getFilterId() != null) { return ctxt.reportBadDefinition(_beanType, String.format( "Cannot serialize %s with `@JsonFormat(shape=ARRAY)` because it also has `@JsonFilter`:" + " property filtering is not compatible with array serialization", ClassUtil.getTypeDescription(_beanType))); } return contextual.asArraySerializer(); } return contextual; } /* /********************************************************************** /* Public accessors /********************************************************************** */ @Override public Iterator properties() { return Arrays.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 {@code false} -- that is, * as-array serializer cannot be used -- if any of following holds true: *
    *
  • has Object Id (may be allowed in future)
  • *
  • has per-property filter (from {@code @JsonFilter}): positions in * array output are implicit, so dropping a property would shift all * values that follow it *
  • *
* * @since 3.0 */ public boolean canCreateArraySerializer() { return (_objectIdWriter == null) // 08-Feb-2025, tatu: [databind#4775] any-getter is fine now //&& (_anyGetterWriter == null) // 28-Jul-2026: as-array output cannot express per-property filtering && (_propertyFilterId == 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; } 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); } 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) { // id may not have been assigned yet (e.g. a `null` id property) if (id == null) { g.writeNull(); } else { 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) { // id may not have been assigned yet (e.g. a `null` id property) if (id == null) { g.writeNull(); } else { 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]; if (prop != null) { prop.serializeAsProperty(bean, g, ctxt); } prop = props[i+2]; if (prop != null) { prop.serializeAsProperty(bean, g, ctxt); } prop = props[i+3]; if (prop != null) { prop.serializeAsProperty(bean, g, ctxt); } left -= 4; i += 4; } while (left > 3); } switch (left) { case 3: prop = props[i++]; if (prop != null) { prop.serializeAsProperty(bean, g, ctxt); } case 2: prop = props[i++]; if (prop != null) { prop.serializeAsProperty(bean, g, ctxt); } case 1: prop = props[i++]; if (prop != null) { prop.serializeAsProperty(bean, g, ctxt); } } } catch (Exception e) { 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(g, "Infinite recursion (StackOverflowError)", e) .prependPath(bean, name); } } /* /********************************************************************** /* Field serialization methods, 2.x /********************************************************************** */ // 28-Oct-2017, tatu: Not yet optimized. Could be, if it seems // commonly useful wrt JsonView filtering /** * Alternative serialization method that gets called when there is a * {@link PropertyFilter} that needs to be called to determine * which properties are to be serialized (and possibly how) */ protected void _serializePropertiesFiltered(Object bean, JsonGenerator g, SerializationContext ctxt, Object filterId) throws JacksonException { final BeanPropertyWriter[] props; final PropertyFilter filter = findPropertyFilter(ctxt, filterId, bean); if (_filteredProps != null && ctxt.getActiveView() != null) { props = _filteredProps; // better also allow missing filter actually.. Falls down if (filter == null) { _serializePropertiesMaybeView(bean, g, ctxt, props); return; } } else { props = _props; if (filter == null) { _serializePropertiesNoView(bean, g, ctxt, props); return; } } // [databind#6410]: Object Id property is metadata, not to be filtered final BeanPropertyWriter idProp = PropertyBasedObjectIdGenerator.findIdProperty(_objectIdWriter); int i = 0; try { for (final int len = props.length; i < len; ++i) { BeanPropertyWriter prop = props[i]; if (prop != null) { // can have nulls in filtered list if (prop == idProp) { prop.serializeAsProperty(bean, g, ctxt); continue; } // [databind#6136]: let the writer route filtering; most defer to // the filter by name, but e.g. an any-getter unpacks its entries // so each is filtered individually, and view-based writers apply // their view check first. Done polymorphically so this works for // all writer and `PropertyFilter` implementations. prop.serializeFilteredAsProperty(bean, g, ctxt, filter); } } } catch (Exception e) { String name = (i == props.length) ? "[anySetter]" : props[i].getName(); wrapAndThrow(ctxt, e, bean, name); } catch (StackOverflowError e) { // Minimize call depth since we are close to fail: final String name = (i == props.length) ? "[anySetter]" : props[i].getName(); throw DatabindException.from(g, "Infinite recursion (StackOverflowError)", e) .prependPath(bean, name); } } protected void _serializeProperties(Object bean, JsonGenerator g, SerializationContext ctxt) throws JacksonException { // NOTE: only called from places where FilterId (JsonView) already checked. if (_filteredProps != null && ctxt.getActiveView() != null) { _serializePropertiesMaybeView(bean, g, ctxt, _filteredProps); } else { _serializePropertiesNoView(bean, g, ctxt, _props); } } /* /********************************************************************** /* Introspection (for schema generation etc) /********************************************************************** */ @Override public void acceptJsonFormatVisitor(JsonFormatVisitorWrapper visitor, JavaType typeHint) { //deposit your output format if (visitor == null) { return; } JsonObjectFormatVisitor objectVisitor = visitor.expectObjectFormat(typeHint); if (objectVisitor == null) { return; } final SerializationContext ctxt = visitor.getContext(); // Filter provider may return `null` for unknown filter id (if configured // to allow that): if so, handle same as no filter (like serialization does) final PropertyFilter filter = (_propertyFilterId == null) ? null : findPropertyFilter(ctxt, _propertyFilterId, null); if (filter != null) { // [databind#6410]: Object Id property is metadata, not to be filtered final BeanPropertyWriter idProp = PropertyBasedObjectIdGenerator.findIdProperty(_objectIdWriter); for (int i = 0, end = _props.length; i < end; ++i) { final BeanPropertyWriter prop = _props[i]; if (prop == idProp) { prop.depositSchemaProperty(objectVisitor, ctxt); } else { filter.depositSchemaProperty(prop, objectVisitor, ctxt); } } } else { Class view = ((_filteredProps == null) || (ctxt == null)) ? null : ctxt.getActiveView(); final BeanPropertyWriter[] props; if (view != null) { props = _filteredProps; } else { props = _props; } for (int i = 0, end = props.length; i < end; ++i) { BeanPropertyWriter prop = props[i]; if (prop != null) { // may be filtered out unconditionally prop.depositSchemaProperty(objectVisitor, ctxt); } } } } @Override public String toString() { return getClass().getSimpleName()+" for "+handledType().getName(); } }