2017-02-10 116 views
0

我使用mongo-driver 3.2.2从Spring Boot应用程序连接到MongoDB。将MongoDB ObjectId序列化为字符串

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

... 

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

目前我API返回_id作为对象:

"_id":{"timestamp":1486646209,"machineIdentifier":14826340,"processIdentifier":16048,"counter":2373754,"time":1486646209000,"date":1486646209000,"timeSecond":1486646209} 

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

回答

0

是的,当然。使用这段代码:

ObjectId objectId = new ObjectId(); // somehow got it 
String stringValue = objectId.toHexString(); 
// And vice versa 
ObjectId restoredObjectId = new ObjectId(stringValue); 
+0

谢谢,但我需要ObjectId总是序列化为一个字符串。我想避免手动做。 – user3170702

+0

没问题。如果您使用Jakson(或任何其他)JSON序列化程序,则只需为包含ObjectId的字段创建自定义。 F.E. http://stackoverflow.com/questions/7161638/how-do-i-use-a-custom-serializer-with-jackson –

相关问题