FlexJSON在反序列化时排除属性 [英] FlexJSON Exclude Properties Upon Deserialization
问题描述
我正在从Web服务收到JSON响应,但由于各种原因,我不希望在最终响应对象中反序列化某些属性。例如,我有:
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
}
我回来的JSON响应有两个属性,但在反序列化时我不希望设置bar。原因是他们发送的属性很长,但是我们的是一个String,所以反序列化会抛出IllegalArgumentException。
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.
另一种选择是解析使用类似json-simple的JSON,删除我想要的属性,将其转换回JSON并将其传递给反序列化器,但是如果可能的话我想避免使用JSON非常大。
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.
有没有办法用ObjectFactory做这个?
Is there a way to do this with an ObjectFactory perhaps?
推荐答案
是的,ObjectFactory可能是用于允许从Long转换为String。只需在您的路径上注册ObjectFactory,如:
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);
}
}
}
你甚至可以注册为String的默认ObjectFactory,它将处理进入反序列化程序的任何String的情况:
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() );
这篇关于FlexJSON在反序列化时排除属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!