Jersey / JAX-RS:将地图作为XML / JSON返回 [英] Jersey/JAX-RS: Return a Map as XML/JSON

查看:100
本文介绍了Jersey / JAX-RS:将地图作为XML / JSON返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用Jersey / JAX-RS框架将 Map 作为XML / JSON文档返回并不是那么明显。它已经支持 List s,但是当涉及 Map 时,没有 MessageBodyWriter 。即使我将 Ma 嵌入到包装类中,XML模式中也没有 map 类型。 / p>

关于如何将Map编组到Jersey中的XML / JSON文档的任何实用建议?

解决方案

我知道回复的时间已经很晚了,但我希望有一天能帮助别人:)
我申请的最简单,最快捷的解决方案是

  @GET 
@Path(/ {messageId})
@Produces(MediaType.APPLICATION_JSON)
public Response getMessage(@PathParam(messageId)long id){
Map< String,String> map = new HashMap<>();
map.put(1,abc);
map.put(2,def);
map.put(3,ghi);

返回Response.status(Status.OK).entity(map).build();
}

输出:
{
1: abc,
2:def,
3:ghi
}



这绝对有帮助你解决了麻烦。


It's not so obvious how to return a Map as an XML/JSON document using the Jersey/JAX-RS framework. It already has support for Lists, but when it comes to Maps, there is no MessageBodyWriter. And even if I were to embed the Ma into a wrapper class, there is no map type in XML schema.

Any practical advice on how to marshal a Map into an XML/JSON document in Jersey?

解决方案

I know its very late to reply, but I'm hoping it will help somebody someday :) The easiest and quickest fix I applied is

@GET
@Path("/{messageId}")
@Produces(MediaType.APPLICATION_JSON)
public Response getMessage(@PathParam("messageId") long id) {
    Map<String, String> map = new HashMap<>();
    map.put("1", "abc");
    map.put("2", "def");
    map.put("3", "ghi");

    return Response.status(Status.OK).entity(map).build();
}

Output: { "1": "abc", "2": "def", "3": "ghi" }

This should definitely help you solve your trouble.

这篇关于Jersey / JAX-RS:将地图作为XML / JSON返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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