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

The following examples show how to use com.fasterxml.jackson.core.JsonParser#currentName() . 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: StdCallbackContext.java    From cloudformation-cli-java-plugin with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private Map<String, Object> readMap(Class<?> type, JsonParser p, DeserializationContext ctxt) throws IOException {
    if (!p.isExpectedStartObjectToken()) {
        throw new JsonParseException(p, "Expected start of object for Map got " + p.currentToken());
    }
    try {
        Map<String, Object> value = (Map<String, Object>) type.getDeclaredConstructor().newInstance();
        JsonToken next = p.nextToken();
        while (next != JsonToken.END_OBJECT) {
            if (next != JsonToken.FIELD_NAME) {
                throw new JsonParseException(p, "Key was not present " + next);
            }
            String key = p.currentName();
            p.nextToken(); // position to next
            Object val = readObject(p, ctxt);
            value.put(key, val);
            next = p.nextToken();
        }
        return value;
    } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
        throw new JsonMappingException(p, "Can not create empty map for class " + type + " @ " + p.getCurrentLocation(),
                                       e);
    }
}
 
Example 2
Source File: MapDeserializer.java    From jackson-datatypes-collections with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public T deserialize(JsonParser p, DeserializationContext ctxt)
        throws IOException
{
    // Ok: must point to START_OBJECT or FIELD_NAME
    JsonToken t = p.currentToken();
    if (t == JsonToken.START_OBJECT) { // If START_OBJECT, move to next; may also be END_OBJECT
        t = p.nextToken();
    }
    if (t != JsonToken.FIELD_NAME && t != JsonToken.END_OBJECT) {
        // !!! 16-Sep-2019, tatu: Should use full generic type, for error message,
        //   but would require more refactoring (to extend `StdDeserializer` f.ex)
        return (T) ctxt.handleUnexpectedToken(ctxt.constructType(handledType()), p);
    }

    I map = createIntermediate();
    for (; p.currentToken() == JsonToken.FIELD_NAME; p.nextToken()) {
        // Must point to field name now
        String fieldName = p.currentName();
        p.nextToken();
        deserializeEntry(map, ctxt, fieldName, p);
    }
    return finish(map);
}
 
Example 3
Source File: JsonParserUtils.java    From proctor with Apache License 2.0 6 votes vote down vote up
/**
 * Consume json object with the given consumer by iterating over its entries
 *
 * @param jsonParser: jsonParser to consume. currentToken() must return START_OBJECT at the beginning.
 * @param consumer:   consumer taking two arguments: json key and the current jsonParser.
 *                    The consumer must only parse and finishes to parse the corresponding value.
 * @throws IOException
 */
static void consumeJson(
        @Nonnull final JsonParser jsonParser,
        final PartialJsonConsumer consumer
) throws IOException {
    // The current position of jsonParser must be "{".
    Preconditions.checkState(jsonParser.currentToken() == JsonToken.START_OBJECT);

    while (jsonParser.nextToken() != JsonToken.END_OBJECT) {
        // The token right after "{" must be field name.
        Preconditions.checkState(jsonParser.currentToken() == JsonToken.FIELD_NAME);

        // Get the current field name.
        final String key = jsonParser.currentName();

        // Go to the next token, which is the beginning of the corresponding value.
        jsonParser.nextToken();

        // consumer must consume the corresponding value.
        consumer.accept(key, jsonParser);
    }
}
 
Example 4
Source File: ValueReader.java    From jackson-jr with Apache License 2.0 6 votes vote down vote up
protected static String _tokenDesc(JsonParser p, JsonToken t) throws IOException {
    if (t == null) {
        return "NULL";
    }
    switch (t) {
    case FIELD_NAME:
        return "JSON Field name '"+p.currentName()+"'";
    case START_ARRAY:
        return "JSON Array";
    case START_OBJECT:
        return "JSON Object";
    case VALUE_FALSE:
        return "'false'";
    case VALUE_NULL:
        return "'null'";
    case VALUE_NUMBER_FLOAT:
    case VALUE_NUMBER_INT:
        return "JSON Number";
    case VALUE_STRING:
        return "JSON String";
    case VALUE_TRUE:
        return "'true'";
    default:
        return t.toString();
    }
}
 
Example 5
Source File: IEnum.java    From mPaaS with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public IEnum<?> deserialize(JsonParser parser,
		DeserializationContext context)
		throws IOException, JsonProcessingException {
	// 目标对象
	Object currentValue = parser.getCurrentValue();
	// 目标对象的字段
	String currentName = parser.currentName();
	// 枚举类型以及值类型
	Class<IEnum<?>> enumType = (Class<IEnum<?>>) BeanUtils
			.findPropertyType(
					currentName, currentValue.getClass());
	Class<?> valueType = TYPE_CACHE.get(enumType);
	if (valueType == null) {
		valueType = ReflectUtil.getActualClass(enumType, IEnum.class,
				"V");
		TYPE_CACHE.put(enumType, valueType);
	}
	// 获取值并转换
	Object value = parser.readValueAs(valueType);
	if (value != null) {
		for (IEnum<?> e : enumType.getEnumConstants()) {
			if (e.getValue().equals(value)) {
				return e;
			}
		}
	}
	return null;
}
 
Example 6
Source File: IEnum.java    From mPass with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public IEnum<?> deserialize(JsonParser parser,
		DeserializationContext context)
		throws IOException, JsonProcessingException {
	// 目标对象
	Object currentValue = parser.getCurrentValue();
	// 目标对象的字段
	String currentName = parser.currentName();
	// 枚举类型以及值类型
	Class<IEnum<?>> enumType = (Class<IEnum<?>>) BeanUtils
			.findPropertyType(
					currentName, currentValue.getClass());
	Class<?> valueType = TYPE_CACHE.get(enumType);
	if (valueType == null) {
		valueType = ReflectUtil.getActualClass(enumType, IEnum.class,
				"V");
		TYPE_CACHE.put(enumType, valueType);
	}
	// 获取值并转换
	Object value = parser.readValueAs(valueType);
	if (value != null) {
		for (IEnum<?> e : enumType.getEnumConstants()) {
			if (e.getValue().equals(value)) {
				return e;
			}
		}
	}
	return null;
}
 
Example 7
Source File: JacksonDeserializer.java    From jjwt with Apache License 2.0 5 votes vote down vote up
@Override
public Object deserialize(JsonParser parser, DeserializationContext context) throws IOException {
    // check if the current claim key is mapped, if so traverse it's value
    String name = parser.currentName();
    if (claimTypeMap != null && name != null && claimTypeMap.containsKey(name)) {
        Class type = claimTypeMap.get(name);
        return parser.readValueAsTree().traverse(parser.getCodec()).readValueAs(type);
    }
    // otherwise default to super
    return super.deserialize(parser, context);
}
 
Example 8
Source File: GuavaImmutableMapDeserializer.java    From jackson-datatypes-collections with Apache License 2.0 4 votes vote down vote up
@Override
protected T _deserializeEntries(JsonParser p, DeserializationContext ctxt)
    throws IOException, JsonProcessingException
{
    final KeyDeserializer keyDes = _keyDeserializer;
    final JsonDeserializer<?> valueDes = _valueDeserializer;
    final TypeDeserializer typeDeser = _valueTypeDeserializer;

    ImmutableMap.Builder<Object, Object> builder = createBuilder();
    for (; p.currentToken() == JsonToken.FIELD_NAME; p.nextToken()) {
        // Must point to field name now
        String fieldName = p.currentName();
        Object key = (keyDes == null) ? fieldName : keyDes.deserializeKey(fieldName, ctxt);
        // And then the value...
        JsonToken t = p.nextToken();
        // 28-Nov-2010, tatu: Should probably support "ignorable properties" in future...
        Object value;            
        if (t == JsonToken.VALUE_NULL) {
            if (!_skipNullValues) {
                value = _nullProvider.getNullValue(ctxt);
                // 14-Sep-2015, tatu: As per [datatype-guava#52], avoid exception due to null
                // TODO: allow reporting problem via a feature, in future?
                if (value != null) {
                    builder.put(key, value);
                }
            }
            continue;
        }
        if (typeDeser == null) {
            value = valueDes.deserialize(p, ctxt);
        } else {
            value = valueDes.deserializeWithType(p, ctxt, typeDeser);
        }
        builder.put(key, value);
    }
    // No class outside of the package will be able to subclass us,
    // and we provide the proper builder for the subclasses we implement.
    @SuppressWarnings("unchecked")
    T map = (T) builder.build();
    return map;
}