java - How to return a JSON object from a HashMap with Moxy and Jersey -
i using jersey 2.17 moxy , have functions :
@produces(application_json) @restricted public list<user> getfriends( @pathparam("user") string user ) { return userdao.getfriends(user); }
user.preferences hashmap
.
it works fine objects except hashmap
gets translated into:
"preferences":{"entry":[{"key":{"type":"string","value":"language"},"value":{"type":"string","value":"en"}},{"key":{"type":"string","value":"country"},"value":{"type":"string","value":"us"}}]}
but return javascript object like:
preferences:{"language":"en","country":"us"}
how can that?
yeah moxy , maps don't work well. it's sad, json nothing more mapped key/value pairs. if want use moxy, need use xmladapter
. in case, way want json, need create type (class) has name of possible preferences. arbitrary key value pairs should in form require, since moxy can't maps, you'll need map own type. instance
public class preferencesadapter extends xmladapter<preference, hashmap<string, string>> { @xmlrootelement public static class preference { public string language; public string country; } @override public hashmap<string, string> unmarshal(preference p) throws exception { hashmap<string, string> map = new hashmap<>(); map.put("language", p.language); map.put("country", p.country); return map; } @override public preference marshal(hashmap<string, string> v) throws exception { preference p = new preference(); p.language = v.get("language"); p.country = v.get("country"); return p; } }
your dto
@xmlrootelement public class user { @xmljavatypeadapter(preferencesadapter.class) public hashmap<string, string> preferences; }
but if we're doing this, why don't use preferences
object in first place instead of map
? rhetorical question. totally understand why wouldn't. 1 of limitations of moxy, makes heavy of jaxb under hood, , jaxb has never played nicely map, sad, said, json nothing more map of key values.
for reason, , many others have encountered in past, no recommend using moxy though recommended jersey. instead, use jackson. jackson has been defacto java goto json processing while. jackson, use dependency
<dependency> <groupid>org.glassfish.jersey.media</groupid> <artifactid>jersey-media-json-jackson</artifactid> <version>${jersey.version}</version> </dependency>
if take out moxy dependency, jackson module should work out box. otherwise if leave moxy dependency, need register jacksonfeature
Comments
Post a Comment