7
我有一个有十几个属性的类。对于基本类型的大多数属性,我希望使用默认的BeanSerializer和BeanDeserializer或其他来减少我需要编写的繁琐代码。对于自定义和数组类型的其他属性,我想做一些自定义的串行器/解串器。请注意,我无法更改基础JSON字符串。但是我完全可以访问android代码。我正在使用杰克逊1.7.9/Ektorp 1.1.1。如何在Jackson中编写自定义串行器和解串器?
我应该继承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;
}
}
我搜索了Google,但找不到任何有用的示例/教程。如果任何人都可以寄给我一些很棒的例子!谢谢!
感谢您的想法!我会试试看看它是否有效。我使用Ektorp for Android,他们建议使用1.1.1,这就是为什么我使用Jackson 1.7.9。但如果我升级它可能会工作。 –
我可以去的最高版本是1.8.5。任何建议?我将在OddType上试用你的JsonSerializer的想法。 –
1.8比1.7有更好的可重写性,所以它可能实际上工作。使用BeanSerializerModifier你实际上不需要重写BeanSerializer,但也可以创建自定义实例,但将其他道具推迟到默认设置。另外,你的自定义序列化器可以在'resolve()'方法中查找默认的序列化器(如果你实现了ResolvableSerializer,类似于BeanSerializer的做法)。理想情况下,如果可能的话,你会避免对BeanSerializers进行子类化,只是为了简单;但是如果你需要子类,那也是一种支持的技术。 – StaxMan