【问题标题】:return Map from rest service in json format以json格式从rest服务返回地图
【发布时间】:2016-05-23 06:45:40
【问题描述】:

我有一个返回 Map<String, ArrayList<EntityClass>> 的方法。代码如下Definition类:

public Map<String, ArrayList<EntityClass>> webMethod1(){
    ArrayList<EntityClass> arr = new ArrayList<>();
    for (int i=0;i<5;i++){
        arr.add(new EntityClass(i, String.valueOf(i)));
    }
    Map<String, ArrayList<EntityClass>> map = new HashMap<>();
    map.put("Entity", arr);
}

进一步这由 Web 服务调用,如下所示:

@GET
@Path("/m1")
@Produces(MediaType.APPLICATION_JSON)
public Map<String, ArrayList<EntityClass>> m1(){
    return new Definition().webMethod1();
}

但我在控制台上得到了关注:

MessageBodyWriter not found for media type=application/json, type=class java.util.HashMap, genericType=class java.util.HashMap.

HTTP 500 错误。

如何解决这个错误

【问题讨论】:

  • 您需要将 Map 转换为 json,使用 Jersey 为您提供的任何包装器/类。
  • 我是新手,你能详细解释一下吗
  • 您使用的是哪个 Jersey 版本? 1.x 还是 2.x?
  • 另见another question。一点点搜索不会是坏事......

标签: java json rest jersey


【解决方案1】:

也许您应该考虑使用像 GSON 这样的简单编组器库。 我最终得到了这段代码:

@GET
@Path("/m1")
@Produces(MediaType.APPLICATION_JSON)
public String webMethod1(){
    ArrayList<EntityClass> arr = new ArrayList<>();
    for (int i=0;i<5;i++){
        arr.add(new EntityClass(i, "\"-'"+String.valueOf(i)));
    }
    Map<String, List<EntityClass>> map = new HashMap<>();
    map.put("Entity", arr);

    GsonBuilder builder = new GsonBuilder();
    Gson gson = builder.create();

    return gson.toJson(map);
}

这对我来说做得很好,并且不会像编写 MessageBodyWriter 那样增加很多复杂性,这对于简单的 POJO 类和结构来说毫无意义。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-18
    • 1970-01-01
    相关资源
    最近更新 更多