javajsonmongodbjerseydbobject

Jersey : response with List<DBObject>


I want to send Json with Jersey. I use mongoDb.

My function to return my objects :

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

And my jersey method to return json :

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

I use POSTMAN. POSTMAN receives 200 but not my JSON. If somebody can help me. Thx.


Solution

  • 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.