Search in sources :

Example 11 with TypeDeserializer

use of com.fasterxml.jackson.databind.jsontype.TypeDeserializer in project jackson-databind by FasterXML.

the class CollectionDeserializer method deserialize.

@Override
public Collection<Object> deserialize(JsonParser p, DeserializationContext ctxt, Collection<Object> result) throws IOException {
    // Ok: must point to START_ARRAY (or equivalent)
    if (!p.isExpectedStartArrayToken()) {
        return handleNonArray(p, ctxt, result);
    }
    // [databind#631]: Assign current value, to be accessible by custom serializers
    p.setCurrentValue(result);
    JsonDeserializer<Object> valueDes = _valueDeserializer;
    final TypeDeserializer typeDeser = _valueTypeDeserializer;
    CollectionReferringAccumulator referringAccumulator = (valueDes.getObjectIdReader() == null) ? null : new CollectionReferringAccumulator(_containerType.getContentType().getRawClass(), result);
    JsonToken t;
    while ((t = p.nextToken()) != JsonToken.END_ARRAY) {
        try {
            Object value;
            if (t == JsonToken.VALUE_NULL) {
                if (_skipNullValues) {
                    continue;
                }
                value = _nullProvider.getNullValue(ctxt);
            } else if (typeDeser == null) {
                value = valueDes.deserialize(p, ctxt);
            } else {
                value = valueDes.deserializeWithType(p, ctxt, typeDeser);
            }
            if (referringAccumulator != null) {
                referringAccumulator.add(value);
            } else {
                result.add(value);
            }
        } catch (UnresolvedForwardReference reference) {
            if (referringAccumulator == null) {
                throw JsonMappingException.from(p, "Unresolved forward reference but no identity info", reference);
            }
            Referring ref = referringAccumulator.handleUnresolvedReference(reference);
            reference.getRoid().appendReferring(ref);
        } catch (Exception e) {
            boolean wrap = (ctxt == null) || ctxt.isEnabled(DeserializationFeature.WRAP_EXCEPTIONS);
            if (!wrap) {
                ClassUtil.throwIfRTE(e);
            }
            throw JsonMappingException.wrapWithPath(e, result, result.size());
        }
    }
    return result;
}
Also used : Referring(com.fasterxml.jackson.databind.deser.impl.ReadableObjectId.Referring) TypeDeserializer(com.fasterxml.jackson.databind.jsontype.TypeDeserializer) IOException(java.io.IOException)

Example 12 with TypeDeserializer

use of com.fasterxml.jackson.databind.jsontype.TypeDeserializer in project jackson-databind by FasterXML.

the class EnumMapDeserializer method deserialize.

@Override
public EnumMap<?, ?> deserialize(JsonParser p, DeserializationContext ctxt, EnumMap result) throws IOException {
    // [databind#631]: Assign current value, to be accessible by custom deserializers
    p.setCurrentValue(result);
    final JsonDeserializer<Object> valueDes = _valueDeserializer;
    final TypeDeserializer typeDeser = _valueTypeDeserializer;
    String keyName;
    while ((keyName = p.nextFieldName()) != null) {
        // but we need to let key deserializer handle it separately, nonetheless
        Enum<?> key = (Enum<?>) _keyDeserializer.deserializeKey(keyName, ctxt);
        if (key == null) {
            if (!ctxt.isEnabled(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL)) {
                return (EnumMap<?, ?>) ctxt.handleWeirdStringValue(_enumClass, keyName, "value not one of declared Enum instance names for %s", _containerType.getKeyType());
            }
            // 24-Mar-2012, tatu: Null won't work as a key anyway, so let's
            //  just skip the entry then. But we must skip the value as well, if so.
            p.nextToken();
            p.skipChildren();
            continue;
        }
        // And then the value...
        JsonToken t = p.nextToken();
        // note: MUST check for nulls separately: deserializers will
        // not handle them (and maybe fail or return bogus data)
        Object value;
        try {
            if (t == JsonToken.VALUE_NULL) {
                if (_skipNullValues) {
                    continue;
                }
                value = _nullProvider.getNullValue(ctxt);
            } else if (typeDeser == null) {
                value = valueDes.deserialize(p, ctxt);
            } else {
                value = valueDes.deserializeWithType(p, ctxt, typeDeser);
            }
        } catch (Exception e) {
            return wrapAndThrow(e, result, keyName);
        }
        result.put(key, value);
    }
    return result;
}
Also used : TypeDeserializer(com.fasterxml.jackson.databind.jsontype.TypeDeserializer) IOException(java.io.IOException)

Example 13 with TypeDeserializer

use of com.fasterxml.jackson.databind.jsontype.TypeDeserializer in project jackson-databind by FasterXML.

the class BeanDeserializerBase method resolve.

/*
    /**********************************************************
    /* Validation, post-processing
    /**********************************************************
     */
/**
     * Method called to finalize setup of this deserializer,
     * after deserializer itself has been registered.
     * This is needed to handle recursive and transitive dependencies.
     */
@Override
public void resolve(DeserializationContext ctxt) throws JsonMappingException {
    ExternalTypeHandler.Builder extTypes = null;
    // if ValueInstantiator can use "creator" approach, need to resolve it here...
    SettableBeanProperty[] creatorProps;
    if (_valueInstantiator.canCreateFromObjectWith()) {
        creatorProps = _valueInstantiator.getFromObjectArguments(ctxt.getConfig());
    // 21-Jun-2015, tatu: This resolution was duplicated later on and seems like
    //    it really should be only done at a later point. So commented out in 2.8.
    //   However, just in case there was a reason for it, leaving commented out
    //   here instead of immediately removing.
    /*
            // also: need to try to resolve 'external' type ids...
            for (SettableBeanProperty prop : creatorProps) {
                if (prop.hasValueTypeDeserializer()) {
                    TypeDeserializer typeDeser = prop.getValueTypeDeserializer();
                    if (typeDeser.getTypeInclusion() == JsonTypeInfo.As.EXTERNAL_PROPERTY) {
                        if (extTypes == null) {
                            extTypes = new ExternalTypeHandler.Builder();
                        }
                        extTypes.addExternal(prop, typeDeser);
                    }
                }
            }
            */
    } else {
        creatorProps = null;
    }
    UnwrappedPropertyHandler unwrapped = null;
    for (SettableBeanProperty origProp : _beanProperties) {
        SettableBeanProperty prop = origProp;
        // May already have deserializer from annotations, if so, skip:
        if (!prop.hasValueDeserializer()) {
            // [databind#125]: allow use of converters
            JsonDeserializer<?> deser = findConvertingDeserializer(ctxt, prop);
            if (deser == null) {
                deser = findDeserializer(ctxt, prop.getType(), prop);
            }
            prop = prop.withValueDeserializer(deser);
        } else {
            // may need contextual version
            JsonDeserializer<Object> deser = prop.getValueDeserializer();
            /* Important! This is the only place where we actually handle "primary"
                 * property deserializers -- call is different from other places.
                 */
            JsonDeserializer<?> cd = ctxt.handlePrimaryContextualization(deser, prop, prop.getType());
            if (cd != deser) {
                prop = prop.withValueDeserializer(cd);
            }
        }
        // Need to link managed references with matching back references
        prop = _resolveManagedReferenceProperty(ctxt, prop);
        // [databind#351]: need to wrap properties that require object id resolution.
        if (!(prop instanceof ManagedReferenceProperty)) {
            prop = _resolvedObjectIdProperty(ctxt, prop);
        }
        // Support unwrapped values (via @JsonUnwrapped)
        SettableBeanProperty u = _resolveUnwrappedProperty(ctxt, prop);
        if (u != null) {
            prop = u;
            if (unwrapped == null) {
                unwrapped = new UnwrappedPropertyHandler();
            }
            unwrapped.addProperty(prop);
            // 12-Dec-2014, tatu: As per [databind#647], we will have problems if
            //    the original property is left in place. So let's remove it now.
            _beanProperties.remove(prop);
            continue;
        }
        // 26-Oct-2016, tatu: Need to have access to value deserializer to know if
        //   merging needed, and now seems to be reasonable time to do that.
        final PropertyMetadata md = prop.getMetadata();
        prop = _resolveMergeAndNullSettings(ctxt, prop, md);
        // non-static inner classes too:
        prop = _resolveInnerClassValuedProperty(ctxt, prop);
        if (prop != origProp) {
            _beanProperties.replace(prop);
            // [databind#795]: Make sure PropertyBasedCreator's properties stay in sync
            if (creatorProps != null) {
                //   fully count on this? May need to revisit in future; seems to hold for now.
                for (int i = 0, len = creatorProps.length; i < len; ++i) {
                    if (creatorProps[i] == origProp) {
                        creatorProps[i] = prop;
                        break;
                    }
                // ... as per above, it is possible we'd need to add this as fallback
                // if (but only if) identity check fails?
                /*
                        if (creatorProps[i].getName().equals(prop.getName())) {
                            creatorProps[i] = prop;
                            break;
                        }
                        */
                }
            }
        }
        // it needs different handling altogether
        if (prop.hasValueTypeDeserializer()) {
            TypeDeserializer typeDeser = prop.getValueTypeDeserializer();
            if (typeDeser.getTypeInclusion() == JsonTypeInfo.As.EXTERNAL_PROPERTY) {
                if (extTypes == null) {
                    extTypes = ExternalTypeHandler.builder(_beanType);
                }
                extTypes.addExternal(prop, typeDeser);
                // In fact, remove from list of known properties to simplify later handling
                _beanProperties.remove(prop);
                continue;
            }
        }
    }
    // "any setter" may also need to be resolved now
    if (_anySetter != null && !_anySetter.hasValueDeserializer()) {
        _anySetter = _anySetter.withValueDeserializer(findDeserializer(ctxt, _anySetter.getType(), _anySetter.getProperty()));
    }
    // as well as delegate-based constructor:
    if (_valueInstantiator.canCreateUsingDelegate()) {
        JavaType delegateType = _valueInstantiator.getDelegateType(ctxt.getConfig());
        if (delegateType == null) {
            ctxt.reportBadDefinition(_beanType, String.format("Invalid delegate-creator definition for %s: value instantiator (%s) returned true for 'canCreateUsingDelegate()', but null for 'getDelegateType()'", _beanType, _valueInstantiator.getClass().getName()));
        }
        _delegateDeserializer = _findDelegateDeserializer(ctxt, delegateType, _valueInstantiator.getDelegateCreator());
    }
    // and array-delegate-based constructor:
    if (_valueInstantiator.canCreateUsingArrayDelegate()) {
        JavaType delegateType = _valueInstantiator.getArrayDelegateType(ctxt.getConfig());
        if (delegateType == null) {
            ctxt.reportBadDefinition(_beanType, String.format("Invalid delegate-creator definition for %s: value instantiator (%s) returned true for 'canCreateUsingArrayDelegate()', but null for 'getArrayDelegateType()'", _beanType, _valueInstantiator.getClass().getName()));
        }
        _arrayDelegateDeserializer = _findDelegateDeserializer(ctxt, delegateType, _valueInstantiator.getArrayDelegateCreator());
    }
    // And now that we know CreatorProperty instances are also resolved can finally create the creator:
    if (creatorProps != null) {
        _propertyBasedCreator = PropertyBasedCreator.construct(ctxt, _valueInstantiator, creatorProps, _beanProperties);
    }
    if (extTypes != null) {
        // 21-Jun-2016, tatu: related to [databind#999], may need to link type ids too,
        //    so need to pass collected properties
        _externalTypeIdHandler = extTypes.build(_beanProperties);
        // we consider this non-standard, to offline handling
        _nonStandardCreation = true;
    }
    _unwrappedPropertyHandler = unwrapped;
    if (unwrapped != null) {
        // we consider this non-standard, to offline handling
        _nonStandardCreation = true;
    }
    // may need to disable vanilla processing, if unwrapped handling was enabled...
    _vanillaProcessing = _vanillaProcessing && !_nonStandardCreation;
}
Also used : TypeDeserializer(com.fasterxml.jackson.databind.jsontype.TypeDeserializer)

Example 14 with TypeDeserializer

use of com.fasterxml.jackson.databind.jsontype.TypeDeserializer in project jackson-databind by FasterXML.

the class BeanDeserializerBase method _findDelegateDeserializer.

private JsonDeserializer<Object> _findDelegateDeserializer(DeserializationContext ctxt, JavaType delegateType, AnnotatedWithParams delegateCreator) throws JsonMappingException {
    // Need to create a temporary property to allow contextual deserializers:
    BeanProperty.Std property = new BeanProperty.Std(TEMP_PROPERTY_NAME, delegateType, null, delegateCreator, PropertyMetadata.STD_OPTIONAL);
    TypeDeserializer td = delegateType.getTypeHandler();
    if (td == null) {
        td = ctxt.getConfig().findTypeDeserializer(delegateType);
    }
    JsonDeserializer<Object> dd = findDeserializer(ctxt, delegateType, property);
    if (td != null) {
        td = td.forProperty(property);
        return new TypeWrappedDeserializer(td, dd);
    }
    return dd;
}
Also used : TypeDeserializer(com.fasterxml.jackson.databind.jsontype.TypeDeserializer)

Example 15 with TypeDeserializer

use of com.fasterxml.jackson.databind.jsontype.TypeDeserializer in project jackson-databind by FasterXML.

the class BeanDeserializerFactory method constructSetterlessProperty.

/**
     * Method that will construct a regular bean property setter using
     * the given setter method.
     */
protected SettableBeanProperty constructSetterlessProperty(DeserializationContext ctxt, BeanDescription beanDesc, BeanPropertyDefinition propDef) throws JsonMappingException {
    final AnnotatedMethod getter = propDef.getGetter();
    JavaType type = resolveMemberAndTypeAnnotations(ctxt, getter, getter.getType());
    TypeDeserializer typeDeser = type.getTypeHandler();
    SettableBeanProperty prop = new SetterlessProperty(propDef, type, typeDeser, beanDesc.getClassAnnotations(), getter);
    JsonDeserializer<?> deser = findDeserializerFromAnnotation(ctxt, getter);
    if (deser == null) {
        deser = type.getValueHandler();
    }
    if (deser != null) {
        deser = ctxt.handlePrimaryContextualization(deser, prop, type);
        prop = prop.withValueDeserializer(deser);
    }
    return prop;
}
Also used : TypeDeserializer(com.fasterxml.jackson.databind.jsontype.TypeDeserializer)

Aggregations

TypeDeserializer (com.fasterxml.jackson.databind.jsontype.TypeDeserializer)30 IOException (java.io.IOException)9 JsonIgnoreProperties (com.fasterxml.jackson.annotation.JsonIgnoreProperties)2 ObjectBuffer (com.fasterxml.jackson.databind.util.ObjectBuffer)2 NullValueProvider (com.fasterxml.jackson.databind.deser.NullValueProvider)1 PropertyBasedCreator (com.fasterxml.jackson.databind.deser.impl.PropertyBasedCreator)1 PropertyValueBuffer (com.fasterxml.jackson.databind.deser.impl.PropertyValueBuffer)1 Referring (com.fasterxml.jackson.databind.deser.impl.ReadableObjectId.Referring)1 TypeWrappedDeserializer (com.fasterxml.jackson.databind.deser.impl.TypeWrappedDeserializer)1 AnnotatedMember (com.fasterxml.jackson.databind.introspect.AnnotatedMember)1