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

时间:2011-10-27 22:47:13

标签: json serialization deserialization jackson 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;
}
}

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

1 个答案:

答案 0 :(得分:4)

对于子类BeanSerializer / -Deserializer,最好使用更新版本的Jackson,因为通过BeanSerializerModifier和BeanDeserializerModifier的显式支持改进了这个区域,这可以改变实例的配置。

但只是为了确保,您还可以指定自定义序列化器/反序列化器,以便在各个属性上使用,如下所示:

class Foo {
   @JsonSerialize(using=MySerializer.class)
   public OddType getValue();
}