我在使用 spring data mongo 模板从 mongo db 检索 JSON 响应时遇到问题。响应不是检索文档的对象 ID,而是带有时间戳。 以下是存储在 mongo 数据库中的 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 消息转换器映射的:
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 中的 rest 端点方法:
@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 而不是发送带有完整时间戳的响应?
即“id”:“5457d80a59b6460a50f6cef1”而不是整个时间戳。
提前谢谢你。
最佳答案
此处的问题与 JSON 响应的 Jackson 序列化有关。这些线程演示了如何连接自定义序列化程序:
关于java - 返回时间戳而不是普通对象 ID 的 Spring Data Mongo 模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26816734/