2017-02-10 63 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 –

相關問題