Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package com.fasterxml.jackson.databind.deser;
  
  import java.util.*;
  
Deserializer class that can deserialize instances of arbitrary bean objects, usually from JSON Object structs, but possibly also from simple types like String values.
 
 public class BeanDeserializer
     extends BeanDeserializerBase
     implements java.io.Serializable
 {
     private static final long serialVersionUID = 1L;
 
     /*
     /**********************************************************
     /* Life-cycle, construction, initialization
     /**********************************************************
      */

    
Constructor used by BeanDeserializerBuilder.
 
     public BeanDeserializer(BeanDeserializerBuilder builder,
             BeanDescription beanDesc,
             BeanPropertyMap propertiesMap<StringSettableBeanPropertybackRefs,
             HashSet<StringignorablePropsboolean ignoreAllUnknown,
             boolean hasViews)
     {
         super(builderbeanDescpropertiesbackRefs,
                 ignorablePropsignoreAllUnknownhasViews);
     }

    
Copy-constructor that can be used by sub-classes to allow copy-on-write style copying of settings of an existing instance.
 
     protected BeanDeserializer(BeanDeserializerBase src) {
         super(srcsrc._ignoreAllUnknown);
     }
 
     protected BeanDeserializer(BeanDeserializerBase srcboolean ignoreAllUnknown) {
         super(srcignoreAllUnknown);
     }
     
     protected BeanDeserializer(BeanDeserializerBase srcNameTransformer unwrapper) {
         super(srcunwrapper);
     }
 
     public BeanDeserializer(BeanDeserializerBase srcObjectIdReader oir) {
         super(srcoir);
     }
 
     public BeanDeserializer(BeanDeserializerBase srcHashSet<StringignorableProps) {
         super(srcignorableProps);
     }
     
     @Override
     {
         /* bit kludgy but we don't want to accidentally change type; sub-classes
          * MUST override this method to support unwrapped properties...
          */
         if (getClass() != BeanDeserializer.class) {
             return this;
         }
         /* main thing really is to just enforce ignoring of unknown
          * properties; since there may be multiple unwrapped values
          * and properties for all may be interleaved...
          */
         return new BeanDeserializer(thisunwrapper);
     }
 
     @Override
         return new BeanDeserializer(thisoir);
     }
 
     @Override
     public BeanDeserializer withIgnorableProperties(HashSet<StringignorableProps) {
         return new BeanDeserializer(thisignorableProps);
     }
 
     @Override
     protected BeanDeserializerBase asArrayDeserializer() {
         return new BeanAsArrayDeserializer(thisprops);
     }
     
     /*
     /**********************************************************
    /* JsonDeserializer implementation
    /**********************************************************
     */

    
Main deserialization method for bean-based objects (POJOs).

NOTE: was declared 'final' in 2.2; should NOT be to let extensions like Afterburner change definition.

    @Override
        throws IOExceptionJsonProcessingException
    {
        JsonToken t = jp.getCurrentToken();
        // common case first:
        if (t == .) {
            if () {
                return vanillaDeserialize(jpctxtjp.nextToken());
            }
            jp.nextToken();
            if ( != null) {
                return deserializeWithObjectId(jpctxt);
            }
            return deserializeFromObject(jpctxt);
        }
        return _deserializeOther(jpctxtt);
    }
    protected final Object _deserializeOther(JsonParser jpDeserializationContext ctxt,
            JsonToken t)
        throws IOExceptionJsonProcessingException
    {
        if (t == null) {
            return _missingToken(jpctxt);
        }
        // and then others, generally requiring use of @JsonCreator
        switch (t) {
        case :
            return deserializeFromString(jpctxt);
        case :
            return deserializeFromNumber(jpctxt);
        case :
	    return deserializeFromDouble(jpctxt);
        case :
            return jp.getEmbeddedObject();
        case :
        case :
            return deserializeFromBoolean(jpctxt);
        case :
            // these only work if there's a (delegating) creator...
            return deserializeFromArray(jpctxt);
        case :
        case // added to resolve [JACKSON-319], possible related issues
            if () {
                return vanillaDeserialize(jpctxtt);
            }
            if ( != null) {
                return deserializeWithObjectId(jpctxt);
            }
            return deserializeFromObject(jpctxt);
        default:
            throw ctxt.mappingException(handledType());
        }
    }
    protected Object _missingToken(JsonParser jpDeserializationContext ctxt)
        throws JsonProcessingException
    {
        throw ctxt.endOfInputException(handledType());
    }
    
    
Secondary deserialization method, called in cases where POJO instance is created as part of deserialization, potentially after collecting some or all of the properties to set.
    @Override
    public Object deserialize(JsonParser jpDeserializationContext ctxtObject bean)
        throws IOExceptionJsonProcessingException
    {
        if ( != null) {
            injectValues(ctxtbean);
        }
        if ( != null) {
            return deserializeWithUnwrapped(jpctxtbean);
        }
        if ( != null) {
            return deserializeWithExternalTypeId(jpctxtbean);
        }
        JsonToken t = jp.getCurrentToken();
        // 23-Mar-2010, tatu: In some cases, we start with full JSON object too...
        if (t == .) {
            t = jp.nextToken();
        }
        if () {
            Class<?> view = ctxt.getActiveView();
            if (view != null) {
                return deserializeWithView(jpctxtbeanview);
            }
        }
        for (; t == .t = jp.nextToken()) {
            String propName = jp.getCurrentName();
            // Skip field name:
            jp.nextToken();
            SettableBeanProperty prop = .find(propName);
            
            if (prop != null) { // normal case
                try {
                    prop.deserializeAndSet(jpctxtbean);
                } catch (Exception e) {
                    wrapAndThrow(ebeanpropNamectxt);
                }
                continue;
            }
            handleUnknownVanilla(jpctxtbeanpropName);
        }
        return bean;
    }
    /*
    /**********************************************************
    /* Concrete deserialization methods
    /**********************************************************
     */

    
Streamlined version that is only used when no "special" features are enabled.
    private final Object vanillaDeserialize(JsonParser jp,
        throws IOExceptionJsonProcessingException
    {
        final Object bean = .createUsingDefault(ctxt);
        for (; jp.getCurrentToken() != .jp.nextToken()) {
            String propName = jp.getCurrentName();
            // Skip field name:
            jp.nextToken();
            SettableBeanProperty prop = .find(propName);
            if (prop != null) { // normal case
                try {
                    prop.deserializeAndSet(jpctxtbean);
                } catch (Exception e) {
                    wrapAndThrow(ebeanpropNamectxt);
                }
            } else {
                handleUnknownVanilla(jpctxtbeanpropName);
            }
        }
        return bean;
    }

    
General version used when handling needs more advanced features.
    @Override
        throws IOExceptionJsonProcessingException
    {
        if () {
            if ( != null) {
                return deserializeWithUnwrapped(jpctxt);
            }
            if ( != null) {
                return deserializeWithExternalTypeId(jpctxt);
            }
            return deserializeFromObjectUsingNonDefault(jpctxt);
        }
        final Object bean = .createUsingDefault(ctxt);
        if (jp.canReadObjectId()) {
            Object id = jp.getObjectId();
            if (id != null) {
                _handleTypedObjectId(jpctxtbeanid);
            }
        }
        if ( != null) {
            injectValues(ctxtbean);
        }
        if () {
            Class<?> view = ctxt.getActiveView();
            if (view != null) {
                return deserializeWithView(jpctxtbeanview);
            }
        }
        for (; jp.getCurrentToken() != .jp.nextToken()) {
            String propName = jp.getCurrentName();
            // Skip field name:
            jp.nextToken();
            SettableBeanProperty prop = .find(propName);
            if (prop != null) { // normal case
                try {
                    prop.deserializeAndSet(jpctxtbean);
                } catch (Exception e) {
                    wrapAndThrow(ebeanpropNamectxt);
                }
                continue;
            }
            handleUnknownVanilla(jpctxtbeanpropName);
        }
        return bean;
    }

    
Method called to deserialize bean using "property-based creator": this means that a non-default constructor or factory method is called, and then possibly other setters. The trick is that values for creator method need to be buffered, first; and due to non-guaranteed ordering possibly some other properties as well.
    @Override
    @SuppressWarnings("resource")
    protected Object _deserializeUsingPropertyBased(final JsonParser jpfinal DeserializationContext ctxt)
        throws IOExceptionJsonProcessingException
    { 
        final PropertyBasedCreator creator = ;
        PropertyValueBuffer buffer = creator.startBuilding(jpctxt);
        
        // 04-Jan-2010, tatu: May need to collect unknown properties for polymorphic cases
        TokenBuffer unknown = null;
        JsonToken t = jp.getCurrentToken();
        for (; t == .t = jp.nextToken()) {
            String propName = jp.getCurrentName();
            jp.nextToken(); // to point to value
            // creator property?
            SettableBeanProperty creatorProp = creator.findCreatorProperty(propName);
            if (creatorProp != null) {
                // Last creator property to set?
                Object value = creatorProp.deserialize(jpctxt);
                if (buffer.assignParameter(creatorProp.getCreatorIndex(), value)) {
                    jp.nextToken(); // to move to following FIELD_NAME/END_OBJECT
                    Object bean;
                    try {
                        bean = creator.build(ctxtbuffer);
                    } catch (Exception e) {
                        wrapAndThrow(e.getRawClass(), propNamectxt);
                        bean = null// never gets here
                    }
                    //  polymorphic?
                    if (bean.getClass() != .getRawClass()) {
                        return handlePolymorphic(jpctxtbeanunknown);
                    }
                    if (unknown != null) { // nope, just extra unknown stuff...
                        bean = handleUnknownProperties(ctxtbeanunknown);
                    }
                    // or just clean?
                    return deserialize(jpctxtbean);
                }
                continue;
            }
            // Object Id property?
            if (buffer.readIdProperty(propName)) {
                continue;
            }
            // regular property? needs buffering
            SettableBeanProperty prop = .find(propName);
            if (prop != null) {
                buffer.bufferProperty(propprop.deserialize(jpctxt));
                continue;
            }
            // As per [JACKSON-313], things marked as ignorable should not be
            // passed to any setter
            if ( != null && .contains(propName)) {
                handleIgnoredProperty(jpctxthandledType(), propName);
                continue;
            }
            // "any property"?
            if ( != null) {
                buffer.bufferAnyProperty(propName.deserialize(jpctxt));
                continue;
            }
            // Ok then, let's collect the whole field; name and value
            if (unknown == null) {
                unknown = new TokenBuffer(jp);
            }
            unknown.writeFieldName(propName);
            unknown.copyCurrentStructure(jp);
        }
        // We hit END_OBJECT, so:
        Object bean;
        try {
            bean =  creator.build(ctxtbuffer);
        } catch (Exception e) {
            wrapInstantiationProblem(ectxt);
            bean = null// never gets here
        }
        if (unknown != null) {
            // polymorphic?
            if (bean.getClass() != .getRawClass()) {
                return handlePolymorphic(nullctxtbeanunknown);
            }
            // no, just some extra unknown properties
            return handleUnknownProperties(ctxtbeanunknown);
        }
        return bean;
    }
    /*
    /**********************************************************
    /* Deserializing when we have to consider an active View
    /**********************************************************
     */
    
    protected final Object deserializeWithView(JsonParser jpDeserializationContext ctxt,
            Object beanClass<?> activeView)
        throws IOExceptionJsonProcessingException
    {
        JsonToken t = jp.getCurrentToken();
        for (; t == .t = jp.nextToken()) {
            String propName = jp.getCurrentName();
            // Skip field name:
            jp.nextToken();
            SettableBeanProperty prop = .find(propName);
            if (prop != null) {
                if (!prop.visibleInView(activeView)) {
                    jp.skipChildren();
                    continue;
                }
                try {
                    prop.deserializeAndSet(jpctxtbean);
                } catch (Exception e) {
                    wrapAndThrow(ebeanpropNamectxt);
                }
                continue;
            }
            handleUnknownVanilla(jpctxtbeanpropName);
        }
        return bean;
    }
    
    /*
    /**********************************************************
    /* Handling for cases where we have "unwrapped" values
    /**********************************************************
     */

    
Method called when there are declared "unwrapped" properties which need special handling
    @SuppressWarnings("resource")
        throws IOExceptionJsonProcessingException
    {
        if ( != null) {
            return .createUsingDelegate(ctxt.deserialize(jpctxt));
        }
        if ( != null) {
            return deserializeUsingPropertyBasedWithUnwrapped(jpctxt);
        }
        TokenBuffer tokens = new TokenBuffer(jp);
        tokens.writeStartObject();
        final Object bean = .createUsingDefault(ctxt);
        if ( != null) {
            injectValues(ctxtbean);
        }
        final Class<?> activeView =  ? ctxt.getActiveView() : null;
        for (; jp.getCurrentToken() != .jp.nextToken()) {
            String propName = jp.getCurrentName();
            jp.nextToken();
            SettableBeanProperty prop = .find(propName);
            if (prop != null) { // normal case
                if (activeView != null && !prop.visibleInView(activeView)) {
                    jp.skipChildren();
                    continue;
                }
                try {
                    prop.deserializeAndSet(jpctxtbean);
                } catch (Exception e) {
                    wrapAndThrow(ebeanpropNamectxt);
                }
                continue;
            }
            // ignorable things should be ignored
            if ( != null && .contains(propName)) {
                handleIgnoredProperty(jpctxtbeanpropName);
                continue;
            }
            // but... others should be passed to unwrapped property deserializers
            tokens.writeFieldName(propName);
            tokens.copyCurrentStructure(jp);
            // how about any setter? We'll get copies but...
            if ( != null) {
                try {
                    .deserializeAndSet(jpctxtbeanpropName);
                } catch (Exception e) {
                    wrapAndThrow(ebeanpropNamectxt);
                }
                continue;
            }
        }
        tokens.writeEndObject();
        .processUnwrapped(jpctxtbeantokens);
        return bean;
    }    
    @SuppressWarnings("resource")
        throws IOExceptionJsonProcessingException
    {
        JsonToken t = jp.getCurrentToken();
        if (t == .) {
            t = jp.nextToken();
        }
        TokenBuffer tokens = new TokenBuffer(jp);
        tokens.writeStartObject();
        final Class<?> activeView =  ? ctxt.getActiveView() : null;
        for (; t == .t = jp.nextToken()) {
            String propName = jp.getCurrentName();
            SettableBeanProperty prop = .find(propName);
            jp.nextToken();
            if (prop != null) { // normal case
                if (activeView != null && !prop.visibleInView(activeView)) {
                    jp.skipChildren();
                    continue;
                }
                try {
                    prop.deserializeAndSet(jpctxtbean);
                } catch (Exception e) {
                    wrapAndThrow(ebeanpropNamectxt);
                }
                continue;
            }
            if ( != null && .contains(propName)) {
                handleIgnoredProperty(jpctxtbeanpropName);
                continue;
            }
            // but... others should be passed to unwrapped property deserializers
            tokens.writeFieldName(propName);
            tokens.copyCurrentStructure(jp);
            // how about any setter? We'll get copies but...
            if ( != null) {
                .deserializeAndSet(jpctxtbeanpropName);
            }
        }
        tokens.writeEndObject();
        .processUnwrapped(jpctxtbeantokens);
        return bean;
    }
    @SuppressWarnings("resource")
        throws IOExceptionJsonProcessingException
    {
        final PropertyBasedCreator creator = ;
        PropertyValueBuffer buffer = creator.startBuilding(jpctxt);
        TokenBuffer tokens = new TokenBuffer(jp);
        tokens.writeStartObject();
        JsonToken t = jp.getCurrentToken();
        for (; t == .t = jp.nextToken()) {
            String propName = jp.getCurrentName();
            jp.nextToken(); // to point to value
            // creator property?
            SettableBeanProperty creatorProp = creator.findCreatorProperty(propName);
            if (creatorProp != null) {
                // Last creator property to set?
                Object value = creatorProp.deserialize(jpctxt);
                if (buffer.assignParameter(creatorProp.getCreatorIndex(), value)) {
                    t = jp.nextToken(); // to move to following FIELD_NAME/END_OBJECT
                    Object bean;
                    try {
                        bean = creator.build(ctxtbuffer);
                    } catch (Exception e) {
                        wrapAndThrow(e.getRawClass(), propNamectxt);
                        continue// never gets here
                    }
                    // if so, need to copy all remaining tokens into buffer
                    while (t == .) {
                        jp.nextToken(); // to skip name
                        tokens.copyCurrentStructure(jp);
                        t = jp.nextToken();
                    }
                    tokens.writeEndObject();
                    if (bean.getClass() != .getRawClass()) {
                        // !!! 08-Jul-2011, tatu: Could probably support; but for now
                        //   it's too complicated, so bail out
                        tokens.close();
                        throw ctxt.mappingException("Can not create polymorphic instances with unwrapped values");
                    }
                    return .processUnwrapped(jpctxtbeantokens);
                }
                continue;
            }
            // Object Id property?
            if (buffer.readIdProperty(propName)) {
                continue;
            }
            // regular property? needs buffering
            SettableBeanProperty prop = .find(propName);
            if (prop != null) {
                buffer.bufferProperty(propprop.deserialize(jpctxt));
                continue;
            }
            /* As per [JACKSON-313], things marked as ignorable should not be
             * passed to any setter
             */
            if ( != null && .contains(propName)) {
                handleIgnoredProperty(jpctxthandledType(), propName);
                continue;
            }
            tokens.writeFieldName(propName);
            tokens.copyCurrentStructure(jp);
            // "any property"?
            if ( != null) {
                buffer.bufferAnyProperty(propName.deserialize(jpctxt));
            }
        }
        // We hit END_OBJECT, so:
        Object bean;
        try {
            bean =  creator.build(ctxtbuffer);
        } catch (Exception e) {
            wrapInstantiationProblem(ectxt);
            return null// never gets here
        }
        return .processUnwrapped(jpctxtbeantokens);
    }
    /*
    /**********************************************************
    /* Handling for cases where we have property/-ies with
    /* external type id
    /**********************************************************
     */
    
        throws IOExceptionJsonProcessingException
    {
        if ( != null) {
            return deserializeUsingPropertyBasedWithExternalTypeId(jpctxt);
        }
        return deserializeWithExternalTypeId(jpctxt.createUsingDefault(ctxt));
    }
    
            Object bean)
        throws IOExceptionJsonProcessingException
    {
        final Class<?> activeView =  ? ctxt.getActiveView() : null;
        final ExternalTypeHandler ext = .start();
        for (; jp.getCurrentToken() != .jp.nextToken()) {
            String propName = jp.getCurrentName();
            jp.nextToken();
            SettableBeanProperty prop = .find(propName);
            if (prop != null) { // normal case
                // [JACKSON-831]: may have property AND be used as external type id:
                if (jp.getCurrentToken().isScalarValue()) {
                    ext.handleTypePropertyValue(jpctxtpropNamebean);
                }
                if (activeView != null && !prop.visibleInView(activeView)) {
                    jp.skipChildren();
                    continue;
                }
                try {
                    prop.deserializeAndSet(jpctxtbean);
                } catch (Exception e) {
                    wrapAndThrow(ebeanpropNamectxt);
                }
                continue;
            }
            // ignorable things should be ignored
            if ( != null && .contains(propName)) {
                handleIgnoredProperty(jpctxtbeanpropName);
                continue;
            }
            // but others are likely to be part of external type id thingy...
            if (ext.handlePropertyValue(jpctxtpropNamebean)) {
                continue;
            }
            // if not, the usual fallback handling:
            if ( != null) {
                try {
                    .deserializeAndSet(jpctxtbeanpropName);
                } catch (Exception e) {
                    wrapAndThrow(ebeanpropNamectxt);
                }
                continue;
            }
            // Unknown: let's call handler method
            handleUnknownProperty(jpctxtbeanpropName);         
        }
        // and when we get this far, let's try finalizing the deal:
        return ext.complete(jpctxtbean);
    }
    @SuppressWarnings("resource")
        throws IOExceptionJsonProcessingException
    {
        final ExternalTypeHandler ext = .start();
        final PropertyBasedCreator creator = ;
        PropertyValueBuffer buffer = creator.startBuilding(jpctxt);
        TokenBuffer tokens = new TokenBuffer(jp);
        tokens.writeStartObject();
        JsonToken t = jp.getCurrentToken();
        for (; t == .t = jp.nextToken()) {
            String propName = jp.getCurrentName();
            jp.nextToken(); // to point to value
            // creator property?
            SettableBeanProperty creatorProp = creator.findCreatorProperty(propName);
            if (creatorProp != null) {
                // first: let's check to see if this might be part of value with external type id:
                if (ext.handlePropertyValue(jpctxtpropNamebuffer)) {
                    ;
                } else {
                    // Last creator property to set?
                    Object value = creatorProp.deserialize(jpctxt);
                    if (buffer.assignParameter(creatorProp.getCreatorIndex(), value)) {
                        t = jp.nextToken(); // to move to following FIELD_NAME/END_OBJECT
                        Object bean;
                        try {
                            bean = creator.build(ctxtbuffer);
                        } catch (Exception e) {
                            wrapAndThrow(e.getRawClass(), propNamectxt);
                            continue// never gets here
                        }
                        // if so, need to copy all remaining tokens into buffer
                        while (t == .) {
                            jp.nextToken(); // to skip name
                            tokens.copyCurrentStructure(jp);
                            t = jp.nextToken();
                        }
                        if (bean.getClass() != .getRawClass()) {
                            // !!! 08-Jul-2011, tatu: Could probably support; but for now
                            //   it's too complicated, so bail out
                            throw ctxt.mappingException("Can not create polymorphic instances with unwrapped values");
                        }
                        return ext.complete(jpctxtbean);
                    }
                }
                continue;
            }
            // Object Id property?
            if (buffer.readIdProperty(propName)) {
                continue;
            }
            // regular property? needs buffering
            SettableBeanProperty prop = .find(propName);
            if (prop != null) {
                buffer.bufferProperty(propprop.deserialize(jpctxt));
                continue;
            }
            // external type id (or property that depends on it)?
            if (ext.handlePropertyValue(jpctxtpropNamenull)) {
                continue;
            }
            /* As per [JACKSON-313], things marked as ignorable should not be
             * passed to any setter
             */
            if ( != null && .contains(propName)) {
                handleIgnoredProperty(jpctxthandledType(), propName);
                continue;
            }
            // "any property"?
            if ( != null) {
                buffer.bufferAnyProperty(propName.deserialize(jpctxt));
            }
        }
        // We hit END_OBJECT; resolve the pieces:
        try {
            return ext.complete(jpctxtbuffercreator);
        } catch (Exception e) {
            wrapInstantiationProblem(ectxt);
            return null// never gets here
        }
    }
New to GrepCode? Check out our FAQ X