我在使用spring数据mongo模板从mongo db检索JSON响应时遇到问题。响应带有时间戳,而不是检索文档的对象ID。 以下是存储在mongo db中的JSON有效负载:
{
"_id" : ObjectId("5457d80a59b6460a50f6cef1"),
"menuId" : 123,
"menuItemId" : 723,
"lastUpdatedDate" : "2014-10-25T20:10:10+0000",
"menuItemJson" : {
....
}
}
以下是来自mongo db的json响应:
{
"id": {
"time": 1415043082000,
"date": 1415043082000,
"timeSecond": 1415043082,
"inc": 1358352113,
"machine": 1505117706,
"new": false,
"timestamp": 1415043082
},
"menuId": 123,
"menuItemId": 723,
"lastUpdatedDate": "2014-10-25T20:10:10+0000",
"menuItemJson": {
......
}
}
以下是我的Java POJO类,它使用spring http message convertor映射:
import org.bson.types.ObjectId;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
@Document(collection = "MenuItem")
public class MenuItemJsonCollection {
@Id
private ObjectId id;
private Integer menuId;
private Integer menuItemId;
....
}
以下是我检索集合的dao方法:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
@Repository
public class MenuDaoImpl implements MenuDao {
@Autowired
private MongoTemplate mongoMenuOrderingTemplate;
@Override
public MenuItemJsonCollection fetchMenuItemById(Long menuItemId) {
Query query = new Query();
query.addCriteria(Criteria.where("id").is(menuItemId));
return mongoMenuOrderingTemplate.findOne(query, MenuItemJsonCollection.class, "MenuDb");
}
}
以下是控制器中的其余端点方法:
@Controller
public class MenuOrderController {
@Autowired
private MenuOrderService menuOrderService;
@RequestMapping(method = RequestMethod.GET, value = "/menuitems/{id}", produces = "application/json")
public ResponseEntity<MenuItemJsonCollection> getMenuItemByMenu(
@PathVariable("id") String menuItemId,
@RequestParam(value = "lastupdatedatetime", required = false) String lastUpdateDateTimeString) {
Long menuItemID = null;
try{
menuItemID = Long.parseLong(menuItemId);
}catch(Exception exe){
throw new ClassifiedsBadRequestException(ErrorMapping.INVALID_PAYLOAD.getErrorCode());
}
if (!ParamValidationUtil.validateNotNullOrEmptyParams(menuItemId) ) {
throw new ClassifiedsBadRequestException(ErrorMapping.MISSING_FIELD.getErrorCode());
} else{
MenuItemJsonCollection menuItem = menuOrderService.fetchMenuItemById(menuItemID, lastUpdateDateTimeString);
if (menuItem == null) {
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
return new ResponseEntity<>(menuItem, HttpStatus.OK);
}
}
}
我应该怎样做只打印id而不是发送带有完整时间戳的响应?
即&#34; id&#34; :&#34; 5457d80a59b6460a50f6cef1&#34;而不是整个时间戳。
提前谢谢。
答案 0 :(得分:3)
这里的问题是杰克逊序列化JSON响应。这些线程演示了如何连接自定义序列化器: