Java Code Examples for com.fasterxml.jackson.core.JsonParser#hasToken()

The following examples show how to use com.fasterxml.jackson.core.JsonParser#hasToken() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LocalDateTimeBaseDeserializer.java    From openemm with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public T deserialize(JsonParser parser, DeserializationContext context) throws IOException {
    JsonToken token = parser.getCurrentToken();

    if (token == JsonToken.VALUE_NULL) {
        return null;
    } else if (token == JsonToken.START_ARRAY) {
        T value;

        parser.nextToken();
        try {
            value = deserializeOne(parser, context);
        } catch (DateTimeException e) {
            throw context.instantiationException(_valueClass, e);
        }

        if (!parser.hasToken(JsonToken.END_ARRAY)) {
            throw context.wrongTokenException(parser, _valueClass, JsonToken.END_ARRAY, "");
        }

        return value;
    } else {
        throw context.wrongTokenException(parser, _valueClass, JsonToken.START_ARRAY, "");
    }
}
 
Example 2
Source File: YearDeserializer.java    From jackson-modules-java8 with Apache License 2.0 6 votes vote down vote up
@Override
public Year deserialize(JsonParser parser, DeserializationContext context) throws IOException
{
    JsonToken t = parser.currentToken();
    if (t == JsonToken.VALUE_STRING) {
        String string = parser.getValueAsString().trim();
        try {
            if (_formatter == null) {
                return Year.parse(string);
            }
            return Year.parse(string, _formatter);
        } catch (DateTimeException e) {
            return _handleDateTimeFormatException(context, e, _formatter, string);
        }
    }
    if (t == JsonToken.VALUE_NUMBER_INT) {
        return Year.of(parser.getIntValue());
    }
    if (t == JsonToken.VALUE_EMBEDDED_OBJECT) {
        return (Year) parser.getEmbeddedObject();
    }
    if (parser.hasToken(JsonToken.START_ARRAY)){
        return _deserializeFromArray(parser, context);
    }
    return _handleUnexpectedToken(context, parser, JsonToken.VALUE_STRING, JsonToken.VALUE_NUMBER_INT);
}
 
Example 3
Source File: CustomCollectionDeserializer.java    From caravan with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public Object deserialize(JsonParser p, DeserializationContext ctxt)
    throws IOException {
  if (_delegateDeserializer != null) {
    return (Collection<Object>) _valueInstantiator.createUsingDelegate(ctxt,
        _delegateDeserializer.deserialize(p, ctxt));
  }
  // Empty String may be ok; bit tricky to check, however, since
  // there is also possibility of "auto-wrapping" of single-element arrays.
  // Hence we only accept empty String here.
  if (p.hasToken(JsonToken.VALUE_STRING)) {
    String str = p.getText();
    if (str.length() == 0) {
      return (Collection<Object>) _valueInstantiator.createFromString(ctxt, str);
    }
  }
  return deserialize(p, ctxt, createDefaultInstance(ctxt));
}
 
Example 4
Source File: LocalDateDeserializer.java    From bootique with Apache License 2.0 6 votes vote down vote up
@Override
public LocalDate deserialize(JsonParser parser, DeserializationContext context) throws IOException {
    if (parser.hasToken(JsonToken.VALUE_STRING)) {
        String string = parser.getText().trim();
        if (string.length() == 0) {
            return null;
        }
        // as per [datatype-jsr310#37], only check for optional (and, incorrect...) time marker 'T'
        // if we are using default formatter
        DateTimeFormatter format = _formatter;
        if (format == DEFAULT_FORMATTER) {
            if (string.contains("T")) {
                return LocalDate.parse(string, DateTimeFormatter.ISO_LOCAL_DATE_TIME);
            }
        }
        return LocalDate.parse(string, format);
    }
    throw context.wrongTokenException(parser, JsonToken.START_ARRAY, "Expected array or string.");
}
 
Example 5
Source File: BeanReader.java    From jackson-jr with Apache License 2.0 6 votes vote down vote up
private final Object _readWithUnknown(JSONReader r, JsonParser p,
        final Object bean, String propName)
    throws IOException
{
    // first, skip current property
    handleUnknown(r, p, propName);
    // then do the rest with looping
    for (; (propName = p.nextFieldName()) != null; ) {
        BeanPropertyReader prop = findProperty(propName);
        if (prop == null) {
            handleUnknown(r, p, propName);
            continue;
        }
        prop.setValueFor(bean, prop.getReader().readNext(r, p));
    }
    if (!p.hasToken(JsonToken.END_OBJECT)) {
        throw _reportProblem(p);
    }                    
    
    return bean;
}
 
Example 6
Source File: MethodProperty.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void deserializeAndSet(JsonParser p, DeserializationContext ctxt,
        Object instance) throws IOException
{
    Object value;
    if (p.hasToken(JsonToken.VALUE_NULL)) {
        if (_skipNulls) {
            return;
        }
        value = _nullProvider.getNullValue(ctxt);
    } else if (_valueTypeDeserializer == null) {
        value = _valueDeserializer.deserialize(p, ctxt);
    } else {
        value = _valueDeserializer.deserializeWithType(p, ctxt, _valueTypeDeserializer);
    }
    try {
        _setter.invoke(instance, value);
    } catch (Exception e) {
        _throwAsIOE(p, e, value);
    }
}
 
Example 7
Source File: ObjectIdValueProperty.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public Object deserializeSetAndReturn(JsonParser p,
		DeserializationContext ctxt, Object instance) throws IOException
{
    /* 02-Apr-2015, tatu: Actually, as per [databind#742], let it be;
     *  missing or null id is needed for some cases, such as cases where id
     *  will be generated externally, at a later point, and is not available
     *  quite yet. Typical use case is with DB inserts.
     */
    // note: no null checks (unlike usually); deserializer should fail if one found
    if (p.hasToken(JsonToken.VALUE_NULL)) {
        return null;
    }
    Object id = _valueDeserializer.deserialize(p, ctxt);
    ReadableObjectId roid = ctxt.findObjectId(id, _objectIdReader.generator, _objectIdReader.resolver);
    roid.bindItem(instance);
    // also: may need to set a property value as well
    SettableBeanProperty idProp = _objectIdReader.idProperty;
    if (idProp != null) {
        return idProp.setAndReturn(instance, id);
    }
    return instance;
}
 
Example 8
Source File: FieldProperty.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public Object deserializeSetAndReturn(JsonParser p,
		DeserializationContext ctxt, Object instance) throws IOException
{
    Object value;
    if (p.hasToken(JsonToken.VALUE_NULL)) {
        if (_skipNulls) {
            return instance;
        }
        value = _nullProvider.getNullValue(ctxt);
    } else if (_valueTypeDeserializer == null) {
        value = _valueDeserializer.deserialize(p, ctxt);
    } else {
        value = _valueDeserializer.deserializeWithType(p, ctxt, _valueTypeDeserializer);
    }
    try {
        _field.set(instance, value);
    } catch (Exception e) {
        _throwAsIOE(p, e, value);
    }
    return instance;
}
 
Example 9
Source File: LocalTimeDeserializer.java    From bootique with Apache License 2.0 5 votes vote down vote up
@Override
public LocalTime deserialize(JsonParser parser, DeserializationContext context) throws IOException {
    if (parser.hasToken(JsonToken.VALUE_STRING)) {
        String string = parser.getText().trim();
        if (string.length() == 0) {
            return null;
        }
        return LocalTime.parse(string, _formatter);
    }

    throw context.wrongTokenException(parser, JsonToken.START_ARRAY, "Expected array or string.");
}
 
Example 10
Source File: EnumReader.java    From jackson-jr with Apache License 2.0 5 votes vote down vote up
@Override
public Object read(JSONReader reader, JsonParser p) throws IOException {
    if (p.hasToken(JsonToken.VALUE_NUMBER_INT)) {
        int ix = p.getIntValue();
        if (ix < 0 || ix >= _byIndex.length) {
            throw new JSONObjectException("Failed to bind Enum "+desc()+" with index "+ix
                    +" (has "+_byIndex.length+" values)");
        }
        return _byIndex[ix];
    }
    return _enum(p.getValueAsString().trim());
}
 
Example 11
Source File: MapReader.java    From jackson-jr with Apache License 2.0 5 votes vote down vote up
@Override
public Object read(JSONReader r, JsonParser p) throws IOException {
    MapBuilder b = r._mapBuilder(_mapType);
    String propName0 = p.nextFieldName();
    if (propName0 == null) {
        if (p.hasToken(JsonToken.END_OBJECT)) {
            return b.emptyMap();
        }
        throw _reportWrongToken(p);
    }
    Object value = _valueReader.readNext(r, p);
    String propName = p.nextFieldName();
    if (propName == null) {
        if (p.hasToken(JsonToken.END_OBJECT)) {
            return b.singletonMap(propName0, value);
        }
        throw _reportWrongToken(p);
    }
    try {
        b = b.start().put(propName0, value);
        while (true) {
            b = b.put(propName, _valueReader.readNext(r, p));
            propName = p.nextFieldName();
            if (propName == null) {
                if (p.hasToken(JsonToken.END_OBJECT)) {
                    return b.build();
                }
                throw _reportWrongToken(p);
            }
        }
    } catch (IllegalArgumentException e) {
        throw JSONObjectException.from(p, e.getMessage());
    }
}
 
Example 12
Source File: RoundingFloatDeserializer.java    From act-platform with ISC License 5 votes vote down vote up
@Override
public Float deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
  if (p.hasToken(JsonToken.VALUE_NUMBER_FLOAT)) {
    return BigDecimal.valueOf(p.getFloatValue())
            .setScale(DECIMAL_POINTS, RoundingMode.HALF_UP)
            .floatValue();
  }

  // Cannot handle input, throw a MismatchedInputException.
  return (Float) ctxt.handleUnexpectedToken(Float.class, p);
}
 
Example 13
Source File: SCPParametersDeserializer.java    From openjavacard-tools with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public SCPParameters deserialize(JsonParser p, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {
    if (p.hasToken(JsonToken.VALUE_STRING)) {
        return SCPParameters.fromString(p.getText());
    }
    return (SCPParameters) ctxt.handleUnexpectedToken(_valueClass, p);
}
 
Example 14
Source File: InnerSerializationBean.java    From Rosetta with Apache License 2.0 5 votes vote down vote up
@Override
public InnerSerializationBean deserialize(JsonParser p,
                                          DeserializationContext ctxt) throws IOException {
  if (p.hasToken(JsonToken.VALUE_STRING)) {
    String[] values = p.getText().split(":");
    return new InnerSerializationBean(values[0], values[1]);
  }
  return null;
}
 
Example 15
Source File: AnyReader.java    From jackson-jr with Apache License 2.0 5 votes vote down vote up
public Map<String, Object> readFromObject(JSONReader r, JsonParser p, MapBuilder b) throws IOException
{
    // First, a minor optimization for empty Maps
    String k;
    if ((k = p.nextFieldName()) == null) {
        if (!p.hasToken(JsonToken.END_OBJECT)) {
            _reportNotEndObject(p);
        }
        return b.emptyMap();
    }
    // and another for singletons...
    String key = fromKey(k);
    Object value = readNext(r, p);

    if ((k = p.nextFieldName()) == null) {
        if (!p.hasToken(JsonToken.END_OBJECT)) {
            _reportNotEndObject(p);
        }
        return b.singletonMap(key, value);
    }
    b = b.start().put(key, value);
    key = fromKey(k);
    value = readNext(r, p);

    // but then it's loop-de-loop
    try {
        b = b.put(key, value);
        while ((k = p.nextFieldName()) != null) {
            b = b.put(fromKey(k), readNext(r, p));
        }
    } catch (IllegalArgumentException e) {
        throw JSONObjectException.from(p, e.getMessage());
    }
    if (!p.hasToken(JsonToken.END_OBJECT)) {
        _reportNotEndObject(p);
    }
    return b.build();
}
 
Example 16
Source File: LocalDateTimeBaseDeserializer.java    From openemm with GNU Affero General Public License v3.0 5 votes vote down vote up
private int getInt(JsonParser parser, DeserializationContext context, int defaultValue, boolean required) throws IOException {
    if (parser.hasToken(JsonToken.VALUE_NUMBER_INT)) {
        int value = parser.getValueAsInt();
        parser.nextToken();
        return value;
    } else {
        if (required) {
            throw context.wrongTokenException(parser, _valueClass, JsonToken.VALUE_NUMBER_INT, "");
        } else {
            return defaultValue;
        }
    }
}
 
Example 17
Source File: MapReader.java    From jackson-jr with Apache License 2.0 4 votes vote down vote up
@Override
public Object readNext(JSONReader r, JsonParser p) throws IOException {
    if (p.nextToken() != JsonToken.START_OBJECT) {
        if (p.hasToken(JsonToken.VALUE_NULL)) {
            return null;
        }
        throw JSONObjectException.from(p, "Unexpected token %s; should get START_OBJECT",
                p.currentToken());
    }
    
    MapBuilder b = r._mapBuilder(_mapType);
    String propName0 = p.nextFieldName();
    if (propName0 == null) {
        if (p.hasToken(JsonToken.END_OBJECT)) {
            return b.emptyMap();
        }
        throw _reportWrongToken(p);
    }
    Object value = _valueReader.readNext(r, p);
    String propName = p.nextFieldName();
    if (propName == null) {
        if (p.hasToken(JsonToken.END_OBJECT)) {
            return b.singletonMap(propName0, value);
        }
        throw _reportWrongToken(p);
    }
    try {
        b = b.start().put(propName0, value);
        while (true) {
            b = b.put(propName, _valueReader.readNext(r, p));
            propName = p.nextFieldName();
            if (propName == null) {
                if (p.hasToken(JsonToken.END_OBJECT)) {
                    return b.build();
                }
                throw _reportWrongToken(p);
            }
        }
    } catch (IllegalArgumentException e) {
        throw JSONObjectException.from(p, e.getMessage());
    }
}
 
Example 18
Source File: YearMonthDeserializer.java    From jackson-modules-java8 with Apache License 2.0 4 votes vote down vote up
@Override
public YearMonth deserialize(JsonParser parser, DeserializationContext context) throws IOException
{
    if (parser.hasToken(JsonToken.VALUE_STRING)) {
        String string = parser.getText().trim();
        if (string.length() == 0) {
            if (!isLenient()) {
                return _failForNotLenient(parser, context, JsonToken.VALUE_STRING);
            }
            return null;
        }
        try {
            return YearMonth.parse(string, _formatter);
        } catch (DateTimeException e) {
            return _handleDateTimeFormatException(context, e, _formatter, string);
        }
    }
    if (parser.isExpectedStartArrayToken()) {
        JsonToken t = parser.nextToken();
        if (t == JsonToken.END_ARRAY) {
            return null;
        }
        if ((t == JsonToken.VALUE_STRING || t == JsonToken.VALUE_EMBEDDED_OBJECT)
                && context.isEnabled(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS)) {
            final YearMonth parsed = deserialize(parser, context);
            if (parser.nextToken() != JsonToken.END_ARRAY) {
                handleMissingEndArrayForSingle(parser, context);
            }
            return parsed;            
        }
        if (t != JsonToken.VALUE_NUMBER_INT) {
            _reportWrongToken(context, JsonToken.VALUE_NUMBER_INT, "years");
        }
        int year = parser.getIntValue();
        int month = parser.nextIntValue(-1);
        if (month == -1) {
            if (!parser.hasToken(JsonToken.VALUE_NUMBER_INT)) {
                _reportWrongToken(context, JsonToken.VALUE_NUMBER_INT, "months");
            }
            month = parser.getIntValue();
        }
        if (parser.nextToken() != JsonToken.END_ARRAY) {
            throw context.wrongTokenException(parser, handledType(), JsonToken.END_ARRAY,
                    "Expected array to end");
        }
        return YearMonth.of(year, month);
    }
    if (parser.hasToken(JsonToken.VALUE_EMBEDDED_OBJECT)) {
        return (YearMonth) parser.getEmbeddedObject();
    }
    return _handleUnexpectedToken(context, parser,
            JsonToken.VALUE_STRING, JsonToken.START_ARRAY);
}
 
Example 19
Source File: MonthDayDeserializer.java    From jackson-modules-java8 with Apache License 2.0 4 votes vote down vote up
@Override
public MonthDay deserialize(JsonParser parser, DeserializationContext context) throws IOException
{
    if (parser.hasToken(JsonToken.VALUE_STRING)) {
        String string = parser.getValueAsString().trim();
        try {
            if (_formatter == null) {
                return MonthDay.parse(string);
            }
            return MonthDay.parse(string, _formatter);
        } catch (DateTimeException e) {
            return _handleDateTimeFormatException(context, e, _formatter, string);
        }
    }
    if (parser.isExpectedStartArrayToken()) {
        JsonToken t = parser.nextToken();
        if (t == JsonToken.END_ARRAY) {
            return null;
        }
        if ((t == JsonToken.VALUE_STRING || t == JsonToken.VALUE_EMBEDDED_OBJECT)
                && context.isEnabled(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS)) {
            final MonthDay parsed = deserialize(parser, context);
            if (parser.nextToken() != JsonToken.END_ARRAY) {
                handleMissingEndArrayForSingle(parser, context);
            }
            return parsed;
        }
        if (t != JsonToken.VALUE_NUMBER_INT) {
            _reportWrongToken(context, JsonToken.VALUE_NUMBER_INT, "month");
        }
        int month = parser.getIntValue();
        int day = parser.nextIntValue(-1);
        if (day == -1) {
            if (!parser.hasToken(JsonToken.VALUE_NUMBER_INT)) {
                _reportWrongToken(context, JsonToken.VALUE_NUMBER_INT, "day");
            }
            day = parser.getIntValue();
        }
        if (parser.nextToken() != JsonToken.END_ARRAY) {
            throw context.wrongTokenException(parser, handledType(), JsonToken.END_ARRAY,
                    "Expected array to end");
        }
        return MonthDay.of(month, day);
    }
    if (parser.hasToken(JsonToken.VALUE_EMBEDDED_OBJECT)) {
        return (MonthDay) parser.getEmbeddedObject();
    }
    return _handleUnexpectedToken(context, parser,
            JsonToken.VALUE_STRING, JsonToken.START_ARRAY);
}
 
Example 20
Source File: JSR310StringParsableDeserializer.java    From jackson-modules-java8 with Apache License 2.0 4 votes vote down vote up
@Override
public Object deserialize(JsonParser p, DeserializationContext ctxt) throws IOException
{
    if (p.hasToken(JsonToken.VALUE_STRING)) {
        final String text = p.getText().trim();
        if (text.length() == 0) {
            CoercionAction act = ctxt.findCoercionAction(logicalType(), _valueClass,
                    CoercionInputShape.EmptyString);
            if (act == CoercionAction.Fail) {
                ctxt.reportInputMismatch(this,
    "Cannot coerce empty String (\"\") to %s (but could if enabling coercion using `CoercionConfig`)",
    _coercedTypeDesc());
            }
            if (act == CoercionAction.AsEmpty) {
                return getEmptyValue(ctxt);
            }
            // None of the types has specific null value
            return null;
        }
        try {
            switch (_typeSelector) {
            case TYPE_PERIOD:
                return Period.parse(text);
            case TYPE_ZONE_ID:
                return ZoneId.of(text);
            case TYPE_ZONE_OFFSET:
                return ZoneOffset.of(text);
            }
        } catch (DateTimeException e) {
            return _handleDateTimeException(ctxt, e, text);
        }
    }
    if (p.hasToken(JsonToken.VALUE_EMBEDDED_OBJECT)) {
        // 20-Apr-2016, tatu: Related to [databind#1208], can try supporting embedded
        //    values quite easily
        return p.getEmbeddedObject();
    }
    if (p.hasToken(JsonToken.START_ARRAY)){
        return _deserializeFromArray(p, ctxt);
    }
    
    throw ctxt.wrongTokenException(p, handledType(), JsonToken.VALUE_STRING, null);
}