Джерси: ответ со списком<DBObject>
Я хочу отправить Джсона с Джерси. Я использую 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. POSTMAN получает 200, но не мой JSON. Если кто-нибудь может мне помочь. Спасибо.
1 ответ
Решение
Я нахожу решение: моя функция для анализа 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;
}
Моя функция вернуть 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();
}
Надеюсь, что это поможет кому-то в этом мире.