我正在使用Java Driver 3.0和MongoDB来通过web服务发送JSON。
当我想将Document对象(org.bson.Document)转换为JSON时,我使用obj.toJson()
,而当我想将JSON转换为Document对象时,我使用Document.parse(json)
。
但是,当我处理Document对象的列表时(在JSON中表示为:[{"field1":1, ...}, {"field1":2, ...}]
),我无法找到一个清晰的方法来进行这些转换。
目前,我想到了以下“技巧”:
From List to JSON: I add the list of documents as a value of a field called "list" in a bigger document. I convert this big document to JSON, and remove what I don't need from the obtained String.
public String toJson(List<Document> docs){ Document doc = new Document("list", docs); String json = doc.toJson(); return json.substring(json.indexOf(":")+2, json.length()-1); }
From JSON to List: I do the opposite by adding this "list" field to the JSON, converting it to a Document and getting only the value of this field from the Document.
public static List<Document> toListOfDocuments(String json){ Document doc = Document.parse("{ \"list\":"+json+"}"); Object list = doc.get("list"); if(list instanceof List<?>) { return (List<Document>) doc.get("list"); } return null ; }
toJson()
方法一样给出相同的结果,特别是对于"_id"字段或时间戳。
有没有干净的方法来做到这一点?
Document
一起使用。只需转换类型即可。 - Blakes Seven