【问题标题】:Jersey : response with List<DBObject>泽西岛:响应 List<DBObject>
【发布时间】:2014-09-01 14:38:56
【问题描述】:

我想用 Jersey 发送 Json。 我使用 mongoDb。

返回对象的函数:

public static List<DBObject> getAll(){
    List<DBObject> toReturn = new ArrayList<DBObject>();
    DBCollection coll = Db.databse.getCollection("Roles");
    DBCursor cursor = coll.find();
    try {
        while(cursor.hasNext()) {
            toReturn.add(cursor.next());
        }
    } finally {
        cursor.close();
    }

    return toReturn;
}

还有我的球衣返回 json 的方法:

@GET
@Path("/")
@Produces(MediaType.APPLICATION_JSON)
public Response getAll(){
      return Response.status(200).entity(Role.getAll()).build();
}

我使用邮递员。 POSTMAN 收到 200 但不是我的 JSON。 如果有人可以帮助我。 谢谢。

【问题讨论】:

    标签: java json mongodb jersey dbobject


    【解决方案1】:

    我找到了解决方案: 我的函数将 dbCollection 解析为 List

    public static List<Role> getAll(){
        Gson gson = new Gson();
        List<Role> toReturn = new ArrayList<Role>();
        DBCollection coll = Db.databse.getCollection("Roles");
        DBCursor cursor = coll.find();
        try {
            while(cursor.hasNext()) {
                System.out.print(cursor.next());
                Role r = gson.fromJson(cursor.next().toString(),Role.class);
                toReturn.add(r);
            }
        } finally {
            cursor.close();
        }
        return toReturn;
    }
    

    我的函数将 List 返回到 json 响应:

    @GET
    @Path("/")
    public Response getAll(){
        List<Role> roleList = new ArrayList<Role>();
        roleList = Role.getAll();
        String json = new Gson().toJson(roleList);
        return Response.status(200).entity(json).build();
    }
    

    希望这能帮助这个世界上的某个人。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-06
      • 1970-01-01
      • 2011-08-02
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多