Bson Document给Java中的Json

Bha*_*nam 7 java json mongodb bson

这是我的代码:

MongoDBSingleton dbSingleton = MongoDBSingleton.getInstance();
MongoDatabase db;

try {
    db = dbSingleton.getTestdb();
    MongoIterable<String> mg = db.listCollectionNames();
    MongoCursor<String> iterator=mg.iterator();

    while (iterator.hasNext()) {
        MongoCollection<Document> table = db.getCollection(iterator.next());

        for (Document doc: table.find()) {  
            System.out.println(doc.toJson());
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

这输出toJson:

"modified" : { "$date" : 1475789185087}
Run Code Online (Sandbox Code Playgroud)

这是我的输出toString:

{"modified":"Fri Oct 07 02:56:25 IST 2016"}
Run Code Online (Sandbox Code Playgroud)

我想在Json中使用String日期格式,怎么做?

Sha*_*Man 8

可悲的是,IMO,MongoDB Java 支持被破坏了。

也就是说@deprecated,您可以使用 mongo-java-driver 中的一个类:

String json = com.mongodb.util.JSON.serialize(document);
System.out.println("JSON serialized Document: " + json);
Run Code Online (Sandbox Code Playgroud)

我正在使用它从Document我可以反序列化的对象生成与 fastxml (jackson) 兼容的 JSON new ObjectMapper().readValue(json, MyObject.class)

但是,我不确定他们希望您使用什么,因为JSON该类已被弃用。但目前,它仍在项目中(从 v3.4.2 开始)。

我在我的 pom 中导入以下内容:

<dependency>
  <groupId>org.mongodb</groupId>
  <artifactId>mongodb-driver-async</artifactId>
  <version>3.4.2</version>
</dependency>
<!-- Sadly, we need the mongo-java-driver solely to serialize
     Document objects in a sane manner -->
<dependency>
  <groupId>org.mongodb</groupId>
  <artifactId>mongo-java-driver</artifactId>
  <version>3.4.2</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)

我使用异步驱动程序实际获取和推送更新到 mongo,非异步驱动程序仅用于JSON.serialize方法的使用。


not*_*est 3

不,不可能生成纯 JSON。请参考此链接

但是,它可以通过两种模式生成 JSON。

1) 严格模式 - 你已经得到的输出

2)外壳模式

外壳模式:-

JsonWriterSettings writerSettings = new JsonWriterSettings(JsonMode.SHELL, true);           
System.out.println(doc.toJson(writerSettings));
Run Code Online (Sandbox Code Playgroud)

输出:-

"createdOn" : ISODate("2016-07-16T16:26:51.951Z")
Run Code Online (Sandbox Code Playgroud)

MongoDB 扩展 JSON