samy-delux samy-delux - 1 year ago 125
JSON Question

Java.util.Map to JSON Object with Jersey / JAXB / Jackson

I've been trying to create a Jersey REST Webservice. I want to receive and emit JSON objects from Java classes like the following:

public class Book {

public String code;

public HashMap<String, String> names;


This should be converted into JSON like this:

"code": "ABC123",
"names": {
"de": "Die fabelhafte Welt der Amelie",
"fr": "Le fabuleux destin d'Amelie Poulain"

However I can not find a standard solution for this. Everybody seems to be implementing his own wrapper solution. This requirement seems extremly basic to me; I can't believe that this is the generally accepted solution to this, especially since Jersey is really one of the more fun parts of Java.

I've also tried upgrading to Jackson 1.8 which only gives me this, which is extremly obfusicated JSON:

"code": "ABC123",
"names": {
"entry": [{
"key": "de",
"value": "Die fabelhafte Welt der Amelie"
"key": "fr",
"value": "Le fabuleux destin d'Amelie Poulain"

Are there any proposed solutions for this?

Jan Jan
Answer Source

I don't know why this isn't the default setting, and it took me a while figuring it out, but if you want working JSON conversion with Jersey, add


to your web.xml and all your problems should be solved.

PS: you also need to get rid of the @XmlRootElement annotations to make it work

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download