Response mongodb objectDB in Jersey API-REST

99封情书 提交于 2019-12-22 09:29:18

问题


I have an API-REST server developed in Jersey framework in Java. I receive a request, the server extracts some info from a MongoDB database. Then, it receives a List and I would like to Response to the request with the same list, without any process.

This is the code I have in order to response to the request:

@POST   
@Path("/{sensor_id: [0-9]+}/data")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public List<DBObject> getSensorsDataById(@PathParam("domain_name") ... ) {
    ...
    List<DBObject> fields = Lists.newArrayList(output.results());
    return fields;
}

If I print the info that I have from MongoDB

for (int i=0; i<fields.size(); i++){
    System.out.println(fields.get(i).toString());   
}

the result is exactly what I want to send as a response to the request.

...
{ "_id" : { "rooms" : 6 , "unit" : "W" , "hour" : 12 , "minute" : 56} , "count" : 42 , "value" : 0}
{ "_id" : { "rooms" : 6 , "unit" : "W" , "hour" : 12 , "minute" : 23} , "count" : 11 , "value" : 14}
{ "_id" : { "rooms" : 6 , "unit" : "W" , "hour" : 12 , "minute" : 55} , "count" : 149 , "value" : 0}
...

But, when I print the info received from the server as a response to the initial request, I have:

[{"partialObject":false},{"partialObject":false},{"partialObject":false},{"partialObject":false}]

So, I would like to know, if anyone knows if it is possible to register a mapping in the jersey ResourceConfig which is able to convert the DBObject (it is an interface) to a String or to a other serialize object with my info.


回答1:


Here's one way you could solve your problem without having to create the mapper and as a side benefit you have complete control over the response:

@POST   
@Path("/{sensor_id: [0-9]+}/data")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response getSensorsDataById(@PathParam("domain_name") ... ) {
    ...
    List<DBObject> fields = Lists.newArrayList(output.results());
    JSONArray json = new JSONArray();
    for (DBObject field : fields) {
        JSONObject joField = new JSONObject(field.toString());
        json.put(joField);
    }

    return Response.ok().entity(json.toString()).build();
}


来源:https://stackoverflow.com/questions/24929671/response-mongodb-objectdb-in-jersey-api-rest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!