泽西岛API-REST中的响应mongodb objectDB [英] Response mongodb objectDB in Jersey API-REST

查看:87
本文介绍了泽西岛API-REST中的响应mongodb objectDB的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用Java的Jersey框架开发的API-REST服务器.我收到一个请求,服务器从MongoDB数据库中提取了一些信息.然后,它会收到一个列表,并且我希望对具有相同列表的请求做出响应,而无需进行任何处理.

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

如果我打印出MongoDB中的信息

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

所以,我想知道,是否有人知道是否可以在球衣ResourceConfig中注册一个映射,该映射能够将DBObject(它是一个接口)转换为String或与我的另一个序列化对象信息.

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.

推荐答案

这是无需创建映射器即可解决问题的一种方法,并且附带的好处是您可以完全控制响应:

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

这篇关于泽西岛API-REST中的响应mongodb objectDB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆