如何在Java中创建自定义JsonDeserializer?

时间:2011-04-10 02:11:38

标签: java json jackson deserialization

我有一个Map<A,B> fieldOfC作为C类的字段。当我尝试用Jackson反序列化C时,会抛出异常,因为它找不到Map的密钥A的反序列化器。所以,我猜解决方案是扩展StdJsonDeserializer并手动完成 我的问题是我找不到一个如何使用解析器和我必须实现的方法“反序列化”的上下文的例子。

任何人都可以为这个简单的例子编写代码,这样我就可以用它作为开始构建真正的反序列化器吗?

public class A{
  private String a1;
  private Integer a2;
}

public class B{
  private String b1;
}

public class C{
  @JsonDeserialize(keyUsing=ADeserializer.class)
  //also tried this: @JsonDeserialize(keyAs=A.class) without success
  private Map<A,B> fieldOfC;
  private String c1;
}

public class ADeserializer extends StdKeyDeserializer {

  protected ADeserializer(Class<A> cls) {
    super(cls);
  }

  protected Object _parse(String key, DeserializationContext ctxt) throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    return mapper.readValue(key, A.class);
  }
}

提前致谢

编辑:谷歌搜索,我发现了test我遇到的同样问题。这正是我的问题

编辑:当我在方法findKeyDeserializer(org.codehaus.jackson.map.DeserializationConfig, org.codehaus.jackson.type.JavaType, org.codehaus.jackson.map.BeanProperty)

中阅读here时,将扩展类从StdDeserializer更改为StdKeyDeserializer

编辑:解决此问题后,我得到了this one相关信息。

1 个答案:

答案 0 :(得分:5)

我是杰克逊的新手,但下面的内容适用于我。

首先,我将一个JsonCreator方法添加到A:

public class A {
    private String a1;
    private Integer a2;
    public String getA1() { return a1; }
    public Integer getA2() { return a2; }
    public void setA1(String a1) { this.a1 = a1; }
    public void setA2(Integer a2) { this.a2 = a2; }

    @JsonCreator
    public static A fromJSON(String val) throws JsonParseException, JsonMappingException, IOException {
        ObjectMapper mapper = new ObjectMapper();
        A a = mapper.readValue(val,A.class);
        return a;
    }
} 

仅此解决了反序列化问题。对我来说更难的部分是正确的键序列化。我在那里做的是定义一个密钥序列化器,它将命名类序列化为JSON序列化,如下所示:

public class KeySerializer extends SerializerBase<Object> {
    private static final SerializerBase<Object> DEFAULT = new StdKeySerializer();

    private Set<Class<?>> objectKeys_ = Collections.synchronizedSet(new HashSet<Class<?>>());

    protected KeySerializer(Class<?>... objectKeys) {
        super(Object.class);
        for(Class<?> cl:objectKeys) {
            objectKeys_.add(cl);
        }
    }


    @Override
    public JsonNode getSchema(SerializerProvider provider, Type typeHint) throws JsonMappingException {
        return DEFAULT.getSchema(provider, typeHint);
    }


    @Override
    public void serialize(Object value, JsonGenerator jgen,
            SerializerProvider provider) throws IOException,
            JsonGenerationException {
        if (objectKeys_.contains(value.getClass())) {
            ObjectMapper mapper = new ObjectMapper();
            StringWriter writer = new StringWriter();
            mapper.writeValue(writer, value);
            jgen.writeFieldName(writer.toString());
        } else {
            DEFAULT.serialize(value, jgen, provider);
        }
    }
}

然后证明它有效,序列化和反序列化C类实例:

    ObjectMapper mapper = new ObjectMapper();
    StdSerializerProvider provider = new StdSerializerProvider();
    provider.setKeySerializer(new KeySerializer(A.class));
    mapper.setSerializerProvider(provider);

    StringWriter out = new StringWriter();
    mapper.writeValue(out, c);
    String json = out.toString();
    System.out.println("JSON= "+json);

    C c2 = mapper.readValue(json, C.class);
    System.out.print("C2= ");
    StringWriter outC2 = new StringWriter();
    mapper.writeValue(outC2, c2);
    System.out.println(outC2.toString());

对我来说,这产生了输出:

JSON= {"c1":"goo","map":{"{\"a1\":\"1ccf\",\"a2\":7376}":{"b1":"5ox"},"{\"a1\":\"1cd2\",\"a2\":7379}":{"b1":"5p0"},"{\"a1\":\"1cd5\",\"a2\":7382}":{"b1":"5p3"},"{\"a1\":\"1cd8\",\"a2\":7385}":{"b1":"5p6"}}}
C2= {"c1":"goo","map":{"{\"a1\":\"1ccf\",\"a2\":7376}":{"b1":"5ox"},"{\"a1\":\"1cd2\",\"a2\":7379}":{"b1":"5p0"},"{\"a1\":\"1cd5\",\"a2\":7382}":{"b1":"5p3"},"{\"a1\":\"1cd8\",\"a2\":7385}":{"b1":"5p6"}}}

我觉得应该用一种更好的方法来说明如何使用注释来序列化密钥,但我无法解决这个问题。