杰克逊:反序列化地图<Object, Object>
Jackson: Serialise Map<Object, Object>
我有以下 classes:
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;
}
当我尝试序列化 class 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 使用 class C 的 ID 作为键,而不是整个对象?
例如
{
"id":52,
"map":{
"5":{
"id":12,
"object":"some string"
},
"7":{
"id":15,
"object":"another string"
}
}
}
我希望找到一个更简单的解决方案,但最终实现了一个自定义序列化程序。
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()));
}
}
我有以下 classes:
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;
}
当我尝试序列化 class 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 使用 class C 的 ID 作为键,而不是整个对象?
例如
{
"id":52,
"map":{
"5":{
"id":12,
"object":"some string"
},
"7":{
"id":15,
"object":"another string"
}
}
}
我希望找到一个更简单的解决方案,但最终实现了一个自定义序列化程序。
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()));
}
}