I am writing a RESTful service using Jersey and the data is stored in a Mongodb database.
I want to get an item from the database and return the JSON format of it to the clients. And here's my code:
try {
MongoClient mongoClient = new MongoClient("localhost", 27017);
DB db = mongoClient.getDB("test");
DBCollection coll = db.getCollection("entities");
// Build search query
BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put("entity_name", entityName);
DBCursor cursor = coll.find(searchQuery);
try {
if (cursor.hasNext()) {
return cursor.next().toString();
} else {
return "Not found.";
}
} finally {
cursor.close();
mongoClient.close();
}
} catch (UnknownHostException e) {
e.printStackTrace();
}
return "System error.";
But the data I get contains a field called id:
"_id":{
"$oid":"525c8a4df33fa1b05dab6e6c"
},
I want to eliminate this field from the result. How to do it?
And the second question is that: Some of the fields in the result are dates. But the result is like:
"publish_date":{
"$date":"1970-01-15T16:48:14.400Z"
},
I want it to be displayed like:
"publish_date":1970-01-15
I was considering using some third-party libraries like Jackson to store all the data and then return a Jackson object to the client (Jersey can transfer a Jackson object to right JSON format data automatically). But in my case, the number of fields are not fixed. I cannot create an entity class to represent the structure of a result.
Do you guys have some good solutions?
Thx!