我试图用任意对象作为序列化/反序列化Map<?, ?>
Jackson版本2.8。该JSON对方应该是夫妻的阵列,即给定如何反序列化与杰克逊的地图<?, ?>?
public class Foo {
public String foo;
public Foo(String foo) {
this.foo = foo;
}
}
public class Bar {
public String bar;
public Bar(String bar) {
this.bar = bar;
}
}
然后
Map<Foo, Bar> map;
map.put(new Foo("foo1"), new Bar("bar1"));
map.put(new Foo("foo2"), new Bar("bar2"));
应此JSON
[
[ { "foo": "foo1" }, { "bar": "bar1" } ],
[ { "foo": "foo2" }, { "bar": "bar2" } ]
]
所以我做了串行一部分
表示public class MapToArraySerializer extends JsonSerializer<Map<?, ?>> {
@Override
public void serialize(Map<?, ?> value, JsonGenerator gen, SerializerProvider serializers)
throws IOException, JsonProcessingException {
gen.writeStartArray();
for (Map.Entry<?, ?> entry : value.entrySet()) {
gen.writeStartArray();
gen.writeObject(entry.getKey());
gen.writeObject(entry.getValue());
gen.writeEndArray();
}
gen.writeEndArray();
}
}
但我有不知道如何写JsonDeserializer
来做相反的工作。有什么建议么?
注:我需要[ [ "key1", "value1" ], [ "key2", "value2" ] ]
符号能够消耗该JSON在JavaScript中new Map(...)
和JSON.stringify(map)
会产生过多的符号(见https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Map)。为了澄清,这样的地图将是其他类的地域,例如,
public class Baz {
@JsonSerialize(using = MapToArraySerializer.class)
@JsonDeserialize(using = ArrayToMapDeserializer.class, keyAs = Foo.class, contentAs = Bar.class)
Map<Foo, Bar> map;
}
和ArrayToMapDeserializer extends JsonDeserializer<Map<?, ?>>
是我寻求帮助的地方。
我认为你是在复杂的。你的JSON不是地图。你为什么使用'Map'来表示它? 'Foo'和'Bar'有任何使它们不同的属性吗? –
在实际使用情况下,'Foo'和'Bar'是复杂的对象,具有'Foo'作为键类型的映射可能是另一个对象的字段。我需要将这个Java地图移植到JavaScript中,JavaScript有它自己的'Map',它以这种形式序列化(请参阅问题中的MDN链接)。 –
是的,它们可能是完全不同的对象(任何Java对象)。我已经更新了这个问题来说明问题。 –