使用Jersey/JAXB/Jackson的Java.util.Map到JSON对象

sam*_*lux 25 java rest json jersey jackson

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

@XmlRootElement
public class Book {

    public String code;

    public HashMap<String, String> names;

}
Run Code Online (Sandbox Code Playgroud)

这应该像这样转换为JSON:

{
    "code": "ABC123",
    "names": {
        "de": "Die fabelhafte Welt der Amelie",
        "fr": "Le fabuleux destin d'Amelie Poulain"
    }
}
Run Code Online (Sandbox Code Playgroud)

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

我也试过升级到Jackson 1.8,它只给了我这个,这是极端虚假的JSON:

{
    "code": "ABC123",
    "names": {
        "entry": [{
            "key": "de",
            "value": "Die fabelhafte Welt der Amelie"
        },
        {
            "key": "fr",
            "value": "Le fabuleux destin d'Amelie Poulain"
        }]
    }
}
Run Code Online (Sandbox Code Playgroud)

有什么建议的解决方案吗?

Jan*_*Jan 24

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

    <init-param>
        <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
        <param-value>true</param-value>
    </init-param>
Run Code Online (Sandbox Code Playgroud)

到你的web.xml,你应该解决所有问题.

PS:你还需要摆脱@XmlRootElement注释才能使其发挥作用

  • 这是服务器端设置.要在客户端上执行此操作:ClientConfig clientConfig = new DefaultClientConfig(); clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING,Boolean.TRUE); 客户端客户端= Client.create(clientConfig); (3认同)

lob*_*234 7

你可以使用google-gson.这是一个示例代码:

    @Test
    public void testGson(){
       Book book = new Book();
       book.code = "1234";
       book.names = new HashMap<String,String>();
       book.names.put("Manish", "Pandit");
       book.names.put("Some","Name");
       String json = new Gson().toJson(book);
       System.out.println(json);
   }
Run Code Online (Sandbox Code Playgroud)

输出是 {"code":"1234","names":{"Some":"Name","Manish":"Pandit"}}