1

我想用泽西岛发送 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。如果有人可以帮助我。谢谢。

4

1 回答 1

2

I find a solution : My function to parse dbCollection to 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;
}

My function to return List<> to json response :

@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();
}

Hope that will help somebody in this world.

于 2014-09-04T10:26:07.757 回答