我試圖用任意對象作爲序列化/反序列化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對象)。我已經更新了這個問題來說明問題。 –