我有一个有十几个属性的类。对于基本类型的大部分属性,我希望使用默认的 BeanSerializer 和 BeanDeserializer 之类的,以减少我需要编写的繁琐代码。对于自定义和数组类型的其他属性,我想做一些自定义序列化器/反序列化器。请注意,我无法更改底层 JSON 字符串。但我可以完全访问 android 代码。我正在使用杰克逊 1.7.9/Ektorp 1.1.1。
我应该继承 BeanDeserializer 吗?我遇到了麻烦。它需要一个没有参数的默认构造函数,但我不知道如何调用超级构造函数。
class MyType{
// a dozen properties with primitive types String, Int, BigDecimal
public Stirng getName();
public void setName(String name);
// properties that require custom deserializer/serializer
public CustomType getCustom();
public void setCustom(CustomType ct);
}
class MyDeserializer extends BeanDeserialzer{
// an exception is throw if I don't have default constructor.
// But BeanDeserializer doesn't have a default constructor
// It has the below constructor that I don't know how to fill in the parameters
public MyDeserializer(AnnotatedClass forClass, JavaType type,
BeanProperty property, CreatorContainer creators,
BeanPropertyMap properties,
Map<String, SettableBeanProperty> backRefs,
HashSet<String> ignorableProps, boolean ignoreAllUnknown,
SettableAnyProperty anySetter) {
super(forClass, type, property, creators, properties, backRefs, ignorableProps,
ignoreAllUnknown, anySetter);
}
@Override
public Object deserialize(JsonParser jp, DeserializationContext dc, Object bean)
throws IOException, JsonProcessingException {
super.deserialize(jp, dc, bean);
MyType c = (MyType)bean;
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readValue(jp, JsonNode.class);
// Use tree model to construct custom
// Is it inefficient because it needs a second pass to the JSON string to construct the tree?
c.setCustom(custom);
return c;
}
}
我搜索了谷歌,但找不到任何有用的示例/教程。如果有人可以给我一些工作示例,那就太好了!谢谢!