我正在尝试使用Jackson 2.8将带有任意对象作为键的
应该用这个JSON来表示。
但我不知道如何编写
注意:我需要使用
为了澄清,这样的映射将是其他类的字段,例如:
Map<?, ?>
进行序列化/反序列化。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" ] ]
表示法才能在JavaScript中消耗该JSON,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<?, ?>>
,这与IT技术有关。
Map
来表示它?Foo
和Bar
有任何不同的属性吗? - cassiomolin