Джерси: ответ со списком <DBObject>

1

Я хочу отправить Джона с Джерси. Я использую 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. Если кто-то может мне помочь. Спасибо.

Теги:
jersey

1 ответ

2
Лучший ответ

Я нахожу решение: моя функция для разбора 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;
}

Моя функция для возврата списка <> в ответ 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();
}

Надеюсь, что это поможет кому-то в этом мире.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню