java - 从rest服务以json格式返回Map

标签 java json rest jersey

我有一个返回 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);
}

此外,这由网络服务调用,如下所示:

@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作为错误。

如何解决此错误

最佳答案

也许您应该考虑使用像 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 类和结构来说是毫无意义的。

关于java - 从rest服务以json格式返回Map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37384225/

相关文章:

java - 多线程 - 如何安全地从 ArrayList 中删除?

java - 在 Java 中提取 zip 存档中的文件时出错

python - Django:使用 Javascript 在我的模板中解析 JSON

python - 访问 Python 字典中的 Unicode 值

java - 如何为 feign bean 字段设置 JsonProperty 名称

java - 如何通过二叉搜索树的广度一阶遍历返回字符串?

java - 私有(private)内部类合成了意外的匿名类

javascript - 为什么我会收到 TypeError : this. getToken is not a function - React JS

python - 如何创建 Perl 代码的 Python 包装器?

http - 用于开发 RESTful Web 服务的工具