2014-09-01 29 views
1

我想向澤西島發送Json。 我使用mongoDb。澤西島:與列表的響應<DBObject>

我的函數返回我的對象​​:

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。 如果有人可以幫助我。 Thx。

回答

2

我找到一個解決方案: 我的函數解析dbCollection列出<>

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; 
} 

我的功能表<>返回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(); 
} 

希望這將有助於有人在這個世界。