我有一个类,有十多个属性。对于基本类型的大多数属性,我希望使用默认的BeanSerializer和BeanDeserializer或其他方法来减少我需要编写的繁琐代码。对于自定义和数组类型的其他属性,我想做一些自定义的序列化器/反序列化器。请注意,我无法更改基础的JSON字符串。但是我可以完全访问android代码。我正在使用Jackson 1.7.9/Ektorp 1.1.1。

我应该将BeanDeserializer子类化吗?我对此感到麻烦。它期望没有参数的默认构造函数,但我不知道如何调用 super 构造函数。

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,但找不到任何有用的示例/教程。如果有人可以给我发送一些工作示例,那就太好了!谢谢!

最佳答案

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

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

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

关于json - 如何在Jackson中编写自定义序列化器和反序列化器?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7923326/

10-09 18:43