我有一个返回 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/