FlexJSON Exclude Properties Upon Deserialization

笑着哭i 提交于 2019-12-08 03:47:42

问题


I'm receiving a JSON response from a web service, but for various reasons I don't want to have certain properties deserialized in the final response object. For example I have:

public class Foo {
    private String bar;
    private int baz;

    //getters & setters
}

The JSON response I'm getting back has both properties, but upon deserialization I don't want "bar" to be set. The reason for this is that the property they're sending is a long, but ours is a String, so deserializing throws an IllegalArgumentException.

Another option would be to parse the JSON with something like json-simple, remove the properties I want, convert it back to JSON and pass that into the deserializer, but I'd like to avoid that if possible since the JSON is pretty large.

Is there a way to do this with an ObjectFactory perhaps?


回答1:


Yes an ObjectFactory could be used to allow a conversion from Long to String. Simply register the ObjectFactory on your path like:

new JSONDeserializer().use("some.path.to.bar", new EnhancedStringObjectFactory() ).deserialize( json, new SomeObject() );



public class EnhancedStringObjectFactory implements ObjectFactory {
    public Object instantiate(ObjectBinder context, Object value, Type targetType, Class targetClass) {
        if( value instanceof String ) {
            return value;
        } else if( value instanceof Number ) {
            return ((Number)value).toString();
        } else {
           throw context.cannotConvertValueToTargetType(value, String.class);
        }
   }
}

You could even register that as the default ObjectFactory for String and it would handle that case for any String coming into the deserializer:

new JSONDeserializer().use( String.class, new EnhancedStringObjectFactory() ).deserialize( json, new SomeObject() );


来源:https://stackoverflow.com/questions/9589644/flexjson-exclude-properties-upon-deserialization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!