Pergunta

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?

Foi útil?

Solução

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() );
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top