将 MongoDB ObjectId 序列化为字符串

use*_*702 5 java spring json mongodb jackson

我正在使用 mongo-driver 3.2.2 从 Spring Boot 应用程序连接到 MongoDB。

public List<Document> getNodes() {
    return mongoDatabase.getCollection("nodes").find().into(new ArrayList<Document>());
}

...

@RequestMapping("/nodes")
public List<Document> nodes(HttpServletResponse response) {
    return mongoRepository.getNodes();
}
Run Code Online (Sandbox Code Playgroud)

目前我的 API_id作为对象返回:

"_id":{"timestamp":1486646209,"machineIdentifier":14826340,"processIdentifier":16048,"counter":2373754,"time":1486646209000,"date":1486646209000,"timeSecond":1486646209}
Run Code Online (Sandbox Code Playgroud)

但我需要它们作为十六进制字符串。有什么方法可以操纵序列化来实现这一点吗?我没有使用实体类。

ale*_*x.b 2

是的,当然。使用这个片段:

ObjectId objectId = new ObjectId(); // somehow got it
String stringValue = objectId.toHexString();
// And vice versa
ObjectId restoredObjectId = new ObjectId(stringValue);
Run Code Online (Sandbox Code Playgroud)