如何在Jackson中编写自定义序列化器和解串器?

Pok*_*com 7 serialization json jackson deserialization ektorp

我有一个有十几个属性的课程.对于原始类型的大多数属性,我希望使用默认的BeanSerializer和BeanDeserializer或其他任何东西来减少我需要编写的繁琐代码.对于自定义和数组类型的其他属性,我想做一些自定义序列化器/反序列化器.请注意,我无法更改基础JSON字符串.但我完全可以访问android代码.我使用Jackson 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;
}
}
Run Code Online (Sandbox Code Playgroud)

我搜索了Google,但找不到任何有用的示例/教程.如果有人能发给我一些很棒的工作实例!谢谢!

Sta*_*Man 4

要子类 BeanSerializer/-Deserializer,您最好使用更新版本的 Jackson,因为该区域已通过 BeanSerializerModifier 和 BeanDeserializerModifier 的显式支持得到改进,这可以更改实例的配置。

但为了确保这一点,您还可以指定自定义序列化器/反序列化器仅用于单个属性,如下所示:

class Foo {
   @JsonSerialize(using=MySerializer.class)
   public OddType getValue();
}
Run Code Online (Sandbox Code Playgroud)