Reputation: 93
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.
Upvotes: 3
Views: 657
Reputation: 2112
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();
}
Upvotes: 1