我有以下代码。我想退回 catalog
中存在的所有文档作为 json 响应。我可以使用 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());
}
}
}
如何将所有文档作为 json 响应返回?如果我的问题很愚蠢,请原谅,我还是个初学者。
编辑 我对代码进行了以下添加:
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();
}
}
目录Pojo.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访问此 url 时,我收到 404。我认为我的 pojo 文件或 List<CatalogPojo>
有问题。
最佳答案
你就快到了。试试这个:
@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();
}
然后使用浏览器或使用 Chorme 插件 PostMan 访问 localhost:xxxx/v1/allmusic。
关于java - 使用 Jersey 从 MongoDb 发送 Json 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46452041/