使用Jersey / JAXB / Jackson的Java.util.Map到JSON对象 [英] Java.util.Map to JSON Object with Jersey / JAXB / Jackson

查看:185
本文介绍了使用Jersey / JAXB / Jackson的Java.util.Map到JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试创建Jersey REST Web服务。我希望从Java类接收和发出JSON对象,如下所示:

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

@XmlRootElement
public class Book {

    public String code;

    public HashMap<String, String> names;

}

这应该像这样转换成JSON:

This should be converted into JSON like this:

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

但是我找不到标准的解决方案。每个人似乎都在实施他自己的包装器 解决方案。这个要求对我来说似乎是极其基本的;我无法相信这是普遍接受的解决方案,特别是因为Jersey真的是Java中最有趣的部分之一。

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.

我也尝试过升级杰克逊1.8这只给了我这个,这是极其荒谬的JSON:

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?

推荐答案

我不知道为什么这不是默认设置,我花了一段时间搞清楚它,但是如果你想用Jersey进行JSON转换,添加

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

    <init-param>
        <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
        <param-value>true</param-value>
    </init-param>

到您的web.xml,所有问题都应该解决。

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

PS:您还需要摆脱 @XmlRootElement 注释才能使其正常工作

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

这篇关于使用Jersey / JAXB / Jackson的Java.util.Map到JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆