Example usage for com.fasterxml.jackson.databind DeserializationContext mappingException

List of usage examples for com.fasterxml.jackson.databind DeserializationContext mappingException

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind DeserializationContext mappingException.

Prototype

public JsonMappingException mappingException(String paramString) 

Source Link

Usage

From source file:com.basistech.rosette.dm.jackson.ListAttributeDeserializer.java

@Override
@SuppressWarnings("unchecked")
public ListAttribute deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
    if (jp.getCurrentToken() == JsonToken.START_OBJECT) { // this is what we expect.
        // we advance to be in the same place the 'else' will be -- the first FIELD_NAME.
        jp.nextToken();//from   www.  j  a  v a 2  s  . co  m
    } else {
        /* In a full AnnotatedText, which is already doing some polymorphism shuffling, we end up here. */
        /* We find a FIELD_NAME for the first field of the object */
        if (jp.getCurrentToken() != JsonToken.FIELD_NAME) {
            throw ctxt.wrongTokenException(jp, JsonToken.START_OBJECT,
                    "ListAttributeDeserializer called not at or FIELD_NAME of first field");
        }
        /* We are at the field name, ready for the loop. */
    }
    TokenBuffer tb = null;
    for (JsonToken t = jp.getCurrentToken(); t == JsonToken.FIELD_NAME; t = jp.nextToken()) {
        String name = jp.getCurrentName();
        if ("itemType".equals(name)) { // gotcha!
            return deserialize(jp, ctxt, tb);
        }
        if (tb == null) {
            tb = new TokenBuffer(null, false);
        }
        tb.copyCurrentStructure(jp);
    }
    throw ctxt.mappingException("No itemType provided in a list");
}

From source file:javaslang.jackson.datatype.deserialize.TupleDeserializer.java

private Tuple create(List<Object> list, DeserializationContext ctxt) throws JsonMappingException {
    final Tuple result;
    switch (list.size()) {
    case 1:/*from ww  w  .j a  v a2  s .c o  m*/
        result = Tuple.of(list.get(0));
        break;
    case 2:
        result = Tuple.of(list.get(0), list.get(1));
        break;
    case 3:
        result = Tuple.of(list.get(0), list.get(1), list.get(2));
        break;
    case 4:
        result = Tuple.of(list.get(0), list.get(1), list.get(2), list.get(3));
        break;
    case 5:
        result = Tuple.of(list.get(0), list.get(1), list.get(2), list.get(3), list.get(4));
        break;
    case 6:
        result = Tuple.of(list.get(0), list.get(1), list.get(2), list.get(3), list.get(4), list.get(5));
        break;
    case 7:
        result = Tuple.of(list.get(0), list.get(1), list.get(2), list.get(3), list.get(4), list.get(5),
                list.get(6));
        break;
    case 8:
        result = Tuple.of(list.get(0), list.get(1), list.get(2), list.get(3), list.get(4), list.get(5),
                list.get(6), list.get(7));
        break;
    default:
        result = Tuple.empty();
    }
    if (!javaType.getRawClass().isAssignableFrom(result.getClass())) {
        throw ctxt.mappingException(javaType.getRawClass());
    }
    return result;
}

From source file:com.basistech.rosette.dm.jackson.ListAttributeDeserializer.java

@SuppressWarnings("unchecked")
private ListAttribute deserialize(JsonParser jp, DeserializationContext ctxt, TokenBuffer tb)
        throws IOException {
    jp.nextToken();//from   w  w  w  .  j a  va  2 s .  c  o m
    String keyName = jp.getText();

    if (tb != null) { // need to put back skipped properties?
        jp = JsonParserSequence.createFlattened(tb.asParser(jp), jp);
    }
    // Must point to the next value; tb had no current, jp pointed to VALUE_STRING:

    KnownAttribute attribute = KnownAttribute.getAttributeForKey(keyName);
    if (attribute == null) {
        attribute = KnownAttribute.UNKNOWN;
    }
    Class<? extends BaseAttribute> itemClass = attribute.attributeClass();

    ListAttribute.Builder<BaseAttribute> builder = new ListAttribute.Builder<>(attribute.attributeClass());
    List<BaseAttribute> items = Lists.newArrayList();

    JsonToken nextToken;
    while ((nextToken = jp.nextToken()) != JsonToken.END_OBJECT) {
        if (nextToken != JsonToken.FIELD_NAME) {
            throw ctxt.wrongTokenException(jp, JsonToken.END_OBJECT, "Expected field name.");
        } else {
            String name = jp.getCurrentName();
            if ("items".equals(name)) {
                // the actual list items.
                nextToken = jp.nextToken();
                if (nextToken == JsonToken.VALUE_EMBEDDED_OBJECT) {
                    Object o = jp.getEmbeddedObject();
                    if (o instanceof List) { // could it be an array, also?!?
                        // when using JsonTree, sometimes Jackson just sticks the entire Java object in here.
                        items.addAll((List) o);
                    } else {
                        throw ctxt.mappingException(
                                "List contains VALUE_EMBEDDED_OBJECT for items, but it wasn't a list.");
                    }
                } else if (nextToken != JsonToken.START_ARRAY) { // what about nothing?
                    throw ctxt.wrongTokenException(jp, JsonToken.START_ARRAY, "Expected array of items");
                } else {
                    // the START_ARRAY case, which is _normal_. Read the elements.
                    while (jp.nextToken() != JsonToken.END_ARRAY) {
                        items.add(jp.readValueAs(itemClass));
                    }
                }
            } else {
                nextToken = jp.nextToken();
                Object value;
                if (nextToken == JsonToken.VALUE_EMBEDDED_OBJECT) {
                    value = jp.getEmbeddedObject();
                } else {
                    value = jp.readValueAs(Object.class);
                }
                builder.extendedProperty(name, value);
            }
        }
    }
    builder.setItems(items);
    return builder.build();
}

From source file:org.hyperledger.dropwizard.hocon.HoconDeserializer.java

protected ConfigList deserializeArray(JsonParser jp, DeserializationContext ctxt) throws IOException {

    List<Object> values = new ArrayList<>();

    JsonToken t;/*from  ww  w. jav a2 s .co m*/
    while ((t = jp.nextToken()) != JsonToken.END_ARRAY) {
        switch (t) {
        case START_ARRAY:
            values.add(deserializeArray(jp, ctxt).unwrapped());
            break;
        case START_OBJECT:
            values.add(deserializeObject(jp, ctxt).unwrapped());
            break;
        case VALUE_FALSE:
            values.add(false);
            break;
        case VALUE_TRUE:
            values.add(true);
            break;
        case VALUE_NULL:
            values.add(null);
            break;
        case VALUE_NUMBER_FLOAT:
            if (jp.getNumberType() == JsonParser.NumberType.BIG_DECIMAL) {
                values.add(jp.getDecimalValue());
            } else {
                values.add(jp.getDoubleValue());
            }
            break;
        case VALUE_NUMBER_INT:
            // very cumbersome... but has to be done
            switch (jp.getNumberType()) {
            case LONG:
                values.add(jp.getLongValue());
                break;
            case INT:
                values.add(jp.getIntValue());
                break;
            default:
                values.add(jp.getBigIntegerValue());
            }
            break;
        case VALUE_STRING:
            values.add(jp.getText());
            break;
        default:
            throw ctxt.mappingException(_valueClass);
        }
    }
    return ConfigValueFactory.fromIterable(values);
}

From source file:com.github.shyiko.jackson.module.advice.AdvisedBeanDeserializer.java

protected Object _deserializeOther(JsonParser jp, DeserializationContext ctxt, JsonToken t) throws IOException {
    if (t == null) {
        return _missingToken(jp, ctxt);
    }/*from   w  ww  . jav a 2  s. c  o m*/
    // and then others, generally requiring use of @JsonCreator
    switch (t) {
    case VALUE_STRING:
        return deserializeFromString(jp, ctxt);
    case VALUE_NUMBER_INT:
        return deserializeFromNumber(jp, ctxt);
    case VALUE_NUMBER_FLOAT:
        return deserializeFromDouble(jp, ctxt);
    case VALUE_EMBEDDED_OBJECT:
        return jp.getEmbeddedObject();
    case VALUE_TRUE:
    case VALUE_FALSE:
        return deserializeFromBoolean(jp, ctxt);
    case START_ARRAY:
        // these only work if there's a (delegating) creator...
        return deserializeFromArray(jp, ctxt);
    case FIELD_NAME:
    case END_OBJECT: // added to resolve [JACKSON-319], possible related issues
        if (_vanillaProcessing) {
            return vanillaDeserialize(jp, ctxt, t);
        }
        if (_objectIdReader != null) {
            return deserializeWithObjectId(jp, ctxt);
        }
        return deserializeFromObject(jp, ctxt);
    default:
        throw ctxt.mappingException(handledType());
    }
}

From source file:org.apache.airavata.db.AbstractThriftDeserializer.java

@Override
public T deserialize(final JsonParser jp, final DeserializationContext ctxt)
        throws IOException, JsonProcessingException {
    final T instance = newInstance();
    final ObjectMapper mapper = (ObjectMapper) jp.getCodec();
    final ObjectNode rootNode = mapper.readTree(jp);
    final Iterator<Map.Entry<String, JsonNode>> iterator = rootNode.fields();

    while (iterator.hasNext()) {
        final Map.Entry<String, JsonNode> currentField = iterator.next();
        try {/*ww w  . ja v a2 s  .co m*/
            /*
             * If the current node is not a null value, process it.  Otherwise,
             * skip it.  Jackson will treat the null as a 0 for primitive
             * number types, which in turn will make Thrift think the field
             * has been set. Also we ignore the MongoDB specific _id field
             */
            if (!currentField.getKey().equalsIgnoreCase("_id")
                    && currentField.getValue().getNodeType() != JsonNodeType.NULL) {
                final E field = getField(
                        CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, currentField.getKey()));
                final JsonParser parser = currentField.getValue().traverse();
                parser.setCodec(mapper);
                final Object value = mapper.readValue(parser, generateValueType(instance, field));
                if (value != null) {
                    log.debug(String.format("Field %s produced value %s of type %s.", currentField.getKey(),
                            value, value.getClass().getName()));
                    instance.setFieldValue(field, value);
                } else {
                    log.debug("Field {} contains a null value.  Skipping...", currentField.getKey());
                }
            } else {
                log.debug("Field {} contains a null value.  Skipping...", currentField.getKey());
            }
        } catch (final NoSuchFieldException | IllegalArgumentException e) {
            log.error("Unable to de-serialize field '{}'.", currentField.getKey(), e);
            ctxt.mappingException(e.getMessage());
        }
    }

    try {
        // Validate that the instance contains all required fields.
        validate(instance);
    } catch (final TException e) {
        log.error(String.format("Unable to deserialize JSON '%s' to type '%s'.", jp.getValueAsString(),
                instance.getClass().getName(), e));
        ctxt.mappingException(e.getMessage());
    }

    return instance;
}

From source file:org.hyperledger.dropwizard.hocon.HoconDeserializer.java

protected ConfigObject deserializeObject(JsonParser jp, DeserializationContext ctxt) throws IOException {
    HashMap<String, Object> mapping = new HashMap<>();

    while (jp.nextToken() != JsonToken.END_OBJECT) {
        String name = jp.getCurrentName();
        JsonToken t = jp.nextToken();// w  w w .  ja  va 2s.c  o m
        switch (t) {
        case START_ARRAY:
            mapping.put(name, deserializeArray(jp, ctxt).unwrapped());
            break;
        case START_OBJECT:
            mapping.put(name, deserializeObject(jp, ctxt).unwrapped());
            break;
        case VALUE_FALSE:
            mapping.put(name, false);
            break;
        case VALUE_TRUE:
            mapping.put(name, true);
            break;
        case VALUE_NULL:
            mapping.put(name, null);
            break;
        case VALUE_NUMBER_FLOAT:
            if (jp.getNumberType() == JsonParser.NumberType.BIG_DECIMAL) {
                mapping.put(name, jp.getDecimalValue());
            } else {
                mapping.put(name, jp.getDoubleValue());
            }
            break;
        case VALUE_NUMBER_INT:
            // very cumbersome... but has to be done
            switch (jp.getNumberType()) {
            case LONG:
                mapping.put(name, jp.getLongValue());
                break;
            case INT:
                mapping.put(name, jp.getIntValue());
                break;
            default:
                mapping.put(name, jp.getBigIntegerValue());
            }
            break;
        case VALUE_STRING:
            mapping.put(name, jp.getText());
            break;
        case VALUE_EMBEDDED_OBJECT: {
            Object ob = jp.getEmbeddedObject();
            if (ob instanceof byte[]) {
                String b64 = ctxt.getBase64Variant().encode((byte[]) ob, false);
                mapping.put(name, b64);
                break;
            }
        }
        default:
            throw ctxt.mappingException(_valueClass);
        }
    }
    return ConfigValueFactory.fromMap(mapping);
}

From source file:org.gvnix.web.json.DataBinderDeserializer.java

/**
 * Deserializes JSON property into Map<String, String> format to use it in a
 * Spring {@link DataBinder}.//from w w w . j a  v a  2 s  .c o  m
 * <p/>
 * Check token's type to perform an action:
 * <ul>
 * <li>If it's a property, stores it in map</li>
 * <li>If it's an object, calls to
 * {@link #readObject(JsonParser, DeserializationContext, String)}</li>
 * <li>If it's an array, calls to
 * {@link #readArray(JsonParser, DeserializationContext, String)}</li>
 * </ul>
 * 
 * @param parser
 * @param ctxt
 * @param token current token
 * @param prefix property dataBinder path
 * @return
 * @throws IOException
 * @throws JsonProcessingException
 */
protected Map<String, String> readField(JsonParser parser, DeserializationContext ctxt, JsonToken token,
        String prefix) throws IOException, JsonProcessingException {

    String fieldName = null;
    String fieldValue = null;

    // Read the field name
    fieldName = parser.getCurrentName();

    // If current token contains a field name
    if (!isEmptyString(fieldName)) {

        // Append the prefix if given
        if (isEmptyString(prefix)) {
            fieldName = parser.getCurrentName();
        } else {
            fieldName = prefix.concat(parser.getCurrentName());
        }
    }
    // If current token contains mark array or object start markers.
    // Note it cannot be a field value because it will be read below and
    // then the token is advanced to the next
    else {

        // Use the prefix in recursive calls
        if (!isEmptyString(prefix)) {
            fieldName = prefix;
        }
    }

    // If current token has been used to read the field name, advance
    // stream to the next token that contains the field value
    if (token == JsonToken.FIELD_NAME) {
        token = parser.nextToken();
    }

    // Field value
    switch (token) {
    case VALUE_STRING:
    case VALUE_NUMBER_INT:
    case VALUE_NUMBER_FLOAT:
    case VALUE_EMBEDDED_OBJECT:
    case VALUE_TRUE:
    case VALUE_FALSE:
        // Plain field: Store value
        Map<String, String> field = new HashMap<String, String>();
        fieldValue = parser.getText();
        field.put(fieldName, fieldValue);
        return field;
    case START_ARRAY:
        // Read array items
        return readArray(parser, ctxt, fieldName);
    case START_OBJECT:
        // Read object properties
        return readObject(parser, ctxt, fieldName);
    case END_ARRAY:
    case END_OBJECT:
        // Skip array and object end markers
        parser.nextToken();
        break;
    default:
        throw ctxt.mappingException(getBeanClass());
    }
    return Collections.emptyMap();
}

From source file:com.github.shyiko.jackson.module.advice.AdvisedBeanDeserializer.java

@SuppressWarnings("resource")
protected Object deserializeUsingPropertyBasedWithUnwrapped(JsonParser jp, DeserializationContext ctxt)
        throws IOException {
    final PropertyBasedCreator creator = _propertyBasedCreator;
    PropertyValueBuffer buffer = creator.startBuilding(jp, ctxt, _objectIdReader);

    TokenBuffer tokens = new TokenBuffer(jp);
    tokens.writeStartObject();// w w w. j  a  va  2 s.  c  o m

    JsonToken t = jp.getCurrentToken();
    for (; t == JsonToken.FIELD_NAME; 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(jp, ctxt);
            if (buffer.assignParameter(creatorProp.getCreatorIndex(), value)) {
                t = jp.nextToken(); // to move to following FIELD_NAME/END_OBJECT
                Object bean;
                try {
                    bean = creator.build(ctxt, buffer);
                } catch (Exception e) {
                    wrapAndThrow(e, _beanType.getRawClass(), propName, ctxt);
                    continue; // never gets here
                }
                // if so, need to copy all remaining tokens into buffer
                while (t == JsonToken.FIELD_NAME) {
                    jp.nextToken(); // to skip name
                    tokens.copyCurrentStructure(jp);
                    t = jp.nextToken();
                }
                tokens.writeEndObject();
                if (bean.getClass() != _beanType.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 _unwrappedPropertyHandler.processUnwrapped(jp, ctxt, bean, tokens);
            }
            continue;
        }
        // Object Id property?
        if (buffer.readIdProperty(propName)) {
            continue;
        }

        // regular property? needs buffering
        SettableBeanProperty prop = _beanProperties.find(propName);
        if (prop != null) {
            buffer.bufferProperty(prop, prop.deserialize(jp, ctxt));
            continue;
        }
        /* As per [JACKSON-313], things marked as ignorable should not be
         * passed to any setter
         */
        if (_ignorableProps != null && _ignorableProps.contains(propName)) {
            handleIgnoredProperty(jp, ctxt, handledType(), propName);
            continue;
        }
        tokens.writeFieldName(propName);
        tokens.copyCurrentStructure(jp);
        // "any property"?
        if (_anySetter != null) {
            buffer.bufferAnyProperty(_anySetter, propName, _anySetter.deserialize(jp, ctxt));
        }
    }

    // We hit END_OBJECT, so:
    Object bean;
    try {
        bean = creator.build(ctxt, buffer);
    } catch (Exception e) {
        wrapInstantiationProblem(e, ctxt);
        return null; // never gets here
    }
    return _unwrappedPropertyHandler.processUnwrapped(jp, ctxt, bean, tokens);
}

From source file:com.github.shyiko.jackson.module.advice.AdvisedBeanDeserializer.java

protected Object deserializeUsingPropertyBasedWithExternalTypeId(JsonParser jp, DeserializationContext ctxt)
        throws IOException {
    final ExternalTypeHandler ext = _externalTypeIdHandler.start();
    final PropertyBasedCreator creator = _propertyBasedCreator;
    PropertyValueBuffer buffer = creator.startBuilding(jp, ctxt, _objectIdReader);

    TokenBuffer tokens = new TokenBuffer(jp);
    tokens.writeStartObject();//from  ww w . j ava2  s .  c o m

    JsonToken t = jp.getCurrentToken();
    for (; t == JsonToken.FIELD_NAME; 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(jp, ctxt, propName, buffer)) {
                // Last creator property to set?
                Object value = creatorProp.deserialize(jp, ctxt);
                if (buffer.assignParameter(creatorProp.getCreatorIndex(), value)) {
                    t = jp.nextToken(); // to move to following FIELD_NAME/END_OBJECT
                    Object bean;
                    try {
                        bean = creator.build(ctxt, buffer);
                    } catch (Exception e) {
                        wrapAndThrow(e, _beanType.getRawClass(), propName, ctxt);
                        continue; // never gets here
                    }
                    // if so, need to copy all remaining tokens into buffer
                    while (t == JsonToken.FIELD_NAME) {
                        jp.nextToken(); // to skip name
                        tokens.copyCurrentStructure(jp);
                        t = jp.nextToken();
                    }
                    if (bean.getClass() != _beanType.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(jp, ctxt, bean);
                }
            }
            continue;
        }
        // Object Id property?
        if (buffer.readIdProperty(propName)) {
            continue;
        }

        // regular property? needs buffering
        SettableBeanProperty prop = _beanProperties.find(propName);
        if (prop != null) {
            buffer.bufferProperty(prop, prop.deserialize(jp, ctxt));
            continue;
        }
        // external type id (or property that depends on it)?
        if (ext.handlePropertyValue(jp, ctxt, propName, null)) {
            continue;
        }
        /* As per [JACKSON-313], things marked as ignorable should not be
         * passed to any setter
         */
        if (_ignorableProps != null && _ignorableProps.contains(propName)) {
            handleIgnoredProperty(jp, ctxt, handledType(), propName);
            continue;
        }
        // "any property"?
        if (_anySetter != null) {
            buffer.bufferAnyProperty(_anySetter, propName, _anySetter.deserialize(jp, ctxt));
        }
    }

    // We hit END_OBJECT; resolve the pieces:
    try {
        return ext.complete(jp, ctxt, buffer, creator);
    } catch (Exception e) {
        wrapInstantiationProblem(e, ctxt);
        return null; // never gets here
    }
}