简体   繁体   English

使用MongoDb的Jersey发送Json响应

[英]Send Json response using Jersey from MongoDb

I have the following code. 我有以下代码。 I want to return all documents present in catalog as a json response. 我想返回catalog存在的所有文档作为json响应。 I am able to print all documents using DBCursor . 我可以使用DBCursor打印所有文档。

@Path("/allmusic")
public class GetAllMusic {

    @Produces(MediaType.APPLICATION_JSON)
    @GET
    public void getAllSongs(@Context HttpHeaders httpHeaders) throws UnknownHostException {

        DB db = (new MongoClient("localhost",27017)).getDB("sampledb");
        DBCollection dbCollection = db.getCollection("catalog");

        DBCursor cursor = dbCollection.find();

        while(cursor.hasNext())
        {
            System.out.println(cursor.next());
        }
    }


}

How can I return all the documents as a json response? 如何返回所有文档作为json响应? Pardon if my question is silly, I am still a beginner. 如果我的问题很傻,请原谅。

EDIT I have made following additions to the code: 编辑我对代码做了以下补充:

GetAllMusic.java GetAllMusic.java

 @Path("/allmusic")
    public class GetAllMusic {
        @GET
        @Produces(MediaType.APPLICATION_JSON)
        @Path("/playlist")
        public Response getAllSongs(@Context HttpHeaders httpHeaders)
         throws UnknownHostException, JsonProcessingException {

                DB db = (new MongoClient("localhost",27017)).getDB("xmusicdb");
                DBCollection dbCollection = db.getCollection("catalog");

                DBCursor cursor = dbCollection.find();

                List<CatalogPojo> result = new ArrayList<>();
                while(cursor.hasNext()) {
                    result.add(new CatalogPojo(cursor.next()));
                }
                String json = new ObjectMapper().writeValueAsString(result);
                return Response.ok(json, MediaType.APPLICATION_JSON).build();
            }

        }

CatalogPojo.java CatalogPojo.java

public class CatalogPojo {

    private String title, artist, album, year;


    /*CatalogPojo(String title, String artist, String album, String year){

    }*/

    public CatalogPojo(DBObject next) {

    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getArtist() {
        return artist;
    }

    public void setArtist(String artist) {
        this.artist = artist;
    }

    public String getAlbum() {
        return album;
    }

    public void setAlbum(String album) {
        this.album = album;
    }

    public String getYear() {
        return year;
    }

    public void setYear(String year) {
        this.year = year;
    }
}

http://localhost:xxxx/xmusic/allmusic/playlist On accessing this url I am getting a 404. I think there is something wrong with my pojo file or List<CatalogPojo> http:// localhost:xxxx / xmusic / allmusic / playlist访问此URL时,我得到的是404。我认为我的pojo文件或List<CatalogPojo>

You're almost there. 你快到了。 Try this: 尝试这个:

@Path("v1")
public class GetAllMusic {
    @GET
    @Path("/allmusic")
    @Produces(MediaType.APPLICATION_JSON)
    public Response getAllSongs {
        ...
        List<AppropriatePojo> result = new ArrayList<>();
        while(cursor.hasNext()) {
            result.add(new AppropriatePojo(cursor.next()));
        }
        String json = new ObjectMapper().writeValueAsString(result);
        return Response.ok(json, MediaType.APPLICATION_JSON).build();
    }

Then access localhost:xxxx/v1/allmusic either with your browser or with thje Chorme plugin PostMan. 然后使用浏览器或Chorme插件PostMan访问localhost:xxxx / v1 / allmusic。

@SOlsson solution is excellent but following code solves the problem in less number of lines. @SOlsson解决方案非常好,但是下面的代码以较少的行数解决了该问题。 It responds with a valid json string. 它以有效的json字符串响应。

@Path("/allmusic")
public class GetAllMusic {

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("/playlist")
    public Response getAllSongs(@Context HttpHeaders httpHeaders) throws UnknownHostException {


        DB db = (new MongoClient("localhost",27017)).getDB("musicdb");
        DBCollection dbCollection = db.getCollection("catalog");
        DBCursor cursor = dbCollection.find();

        JSON json =new JSON();
        @SuppressWarnings("static-access")
        String serialize = json.serialize(cursor);
        System.out.println(serialize);

        return Response.ok(serialize, MediaType.APPLICATION_JSON).build();
    }   
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM