Java.util.Map to JSON Object with Jersey/JAXB/Jackson [英] Java.util.Map to JSON Object with Jersey / JAXB / Jackson
问题描述
我一直在尝试创建 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"
}
}
但是我找不到一个标准的解决方案.每个人似乎都在实现自己的 wrapper 解决方案.这个要求对我来说似乎非常基本;我不敢相信这是普遍接受的解决方案,尤其是因为 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.
我也尝试升级到 Jackson 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
这篇关于Java.util.Map to JSON Object with Jersey/JAXB/Jackson的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!