java - Deserialization of map with integer keys using Jackson -
i have serialize simple integer-to-string map json , read back. serialization pretty simple, since json keys must strings resulting json looks like:
{ "123" : "hello", "456" : "bye", }
when read using code like:
new objectmapper().readvalue(json, map.class)
i map<string, string>
instead of map<integer, string>
need.
i tried add key deserializer following:
map<integer, string> map1 = new hashmap<>(); map1.put(1, "foo"); map1.put(2, "bar"); objectmapper mapper = new objectmapper(); simplemodule module = new simplemodule(); module.addkeydeserializer(integer.class, new keydeserializer() { @override public object deserializekey(string key, deserializationcontext ctxt) throws ioexception, jsonprocessingexception { system.out.println("deserialize " + key); return integer.parseint(key); } }); mapper.registermodule(module); string json = mapper.writevalueasstring(map1); map map2 = mapper.readvalue(json, map.class); system.out.println(map2); system.out.println(map2.keyset().iterator().next().getclass());
unfortunately key deserialzier never called , map2
in fact map<string, string>
, example prints:
{1=foo, 2=bar} class java.lang.string
what doing wrong , how fix problem?
use
map<integer, string> map2 = mapper.readvalue(json, new typereference<map<integer, string>>(){});
or
map<integer, string> map2 = mapper.readvalue(json, typefactory.defaultinstance() .constructmaptype(hashmap.class, integer.class, string.class));
your program output below text:
deserialize 1 deserialize 2 {1=foo, 2=bar} class java.lang.integer
Comments
Post a Comment