杰克逊:Serialise Map <object,object =“”>

时间:2018-04-14 12:54:10

标签: jackson jpa-2.0 jackson2

我有以下课程:

public class A {
    @Id
    private Integer id;
    private String value;
}

public class B {
    @Id
    private Integer id;
    private Map<A, C> map;
}

public class C {
    @Id
    private Integer id;
    private String object;
}

当我尝试序列化B类时,我会得到这样的结果:

{
   "id":52,
   "map":{
      "com.project.model.A@5abbb6ce":{
         "id":12,
         "object":"some string"
      },
      "com.project.model.A@1d1c0771":{
         "id":15,
         "object":"another string"
      }
   }
}

如何让Jackson使用C类的id作为键,而不是整个对象?

E.g

{
   "id":52,
   "map":{
      "5":{
         "id":12,
         "object":"some string"
      },
      "7":{
         "id":15,
         "object":"another string"
      }
   }
}

1 个答案:

答案 0 :(得分:0)

我希望找到一个更简单的解决方案,但最终实现了一个自定义序列化器。

public class B {
    @Id
    private Integer id;

    @JsonSerialize(keyUsing = CustomASerializer.class)
    private Map<A, C> map;
}



public class CustomASerializer extends JsonSerializer<A> {

    @Override
    public void serialize(A a, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        jsonGenerator.writeString(String.valueOf(a.getId()));
    }
}