Search in sources :

Example 1 with FieldTypeResolver

use of com.alibaba.fastjson.parser.deserializer.FieldTypeResolver in project fastjson by alibaba.

the class JSON method parseObject.

@SuppressWarnings("unchecked")
public static <T> T parseObject(String input, Type clazz, ParserConfig config, ParseProcess processor, int featureValues, Feature... features) {
    if (input == null) {
        return null;
    }
    if (features != null) {
        for (Feature feature : features) {
            featureValues |= feature.mask;
        }
    }
    DefaultJSONParser parser = new DefaultJSONParser(input, config, featureValues);
    if (processor != null) {
        if (processor instanceof ExtraTypeProvider) {
            parser.getExtraTypeProviders().add((ExtraTypeProvider) processor);
        }
        if (processor instanceof ExtraProcessor) {
            parser.getExtraProcessors().add((ExtraProcessor) processor);
        }
        if (processor instanceof FieldTypeResolver) {
            parser.setFieldTypeResolver((FieldTypeResolver) processor);
        }
    }
    T value = (T) parser.parseObject(clazz, null);
    parser.handleResovleTask(value);
    parser.close();
    return (T) value;
}
Also used : FieldTypeResolver(com.alibaba.fastjson.parser.deserializer.FieldTypeResolver) DefaultJSONParser(com.alibaba.fastjson.parser.DefaultJSONParser) ExtraTypeProvider(com.alibaba.fastjson.parser.deserializer.ExtraTypeProvider) ExtraProcessor(com.alibaba.fastjson.parser.deserializer.ExtraProcessor) SerializerFeature(com.alibaba.fastjson.serializer.SerializerFeature) Feature(com.alibaba.fastjson.parser.Feature)

Example 2 with FieldTypeResolver

use of com.alibaba.fastjson.parser.deserializer.FieldTypeResolver in project fastjson by alibaba.

the class FieldTypeResolverTest method test_0.

public void test_0() throws Exception {
    String text = "{\"item_0\":{},\"item_1\":{}}";
    FieldTypeResolver fieldResolver = new FieldTypeResolver() {

        public Type resolve(Object object, String fieldName) {
            if (fieldName.startsWith("item_")) {
                return Item.class;
            }
            return null;
        }
    };
    JSONObject jsonObject = JSON.parseObject(text, JSONObject.class, fieldResolver);
    Assert.assertTrue(jsonObject.get("item_0") instanceof Item);
}
Also used : JSONObject(com.alibaba.fastjson.JSONObject) FieldTypeResolver(com.alibaba.fastjson.parser.deserializer.FieldTypeResolver) JSONObject(com.alibaba.fastjson.JSONObject)

Aggregations

FieldTypeResolver (com.alibaba.fastjson.parser.deserializer.FieldTypeResolver)2 JSONObject (com.alibaba.fastjson.JSONObject)1 DefaultJSONParser (com.alibaba.fastjson.parser.DefaultJSONParser)1 Feature (com.alibaba.fastjson.parser.Feature)1 ExtraProcessor (com.alibaba.fastjson.parser.deserializer.ExtraProcessor)1 ExtraTypeProvider (com.alibaba.fastjson.parser.deserializer.ExtraTypeProvider)1 SerializerFeature (com.alibaba.fastjson.serializer.SerializerFeature)1