在Java中将Bson文档转换为Json

10
这是我的代码:
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());
        }
    }

}

这是toJson的输出结果:
"modified" : { "$date" : 1475789185087}

这是我的toString输出结果:
{"modified":"Fri Oct 07 02:56:25 IST 2016"}

我想在Json中使用字符串日期格式,应该怎么做?


你的 MongoDB 版本和 Java 驱动版本是什么? - notionquest
我的Mongo版本是3.2,驱动程序是3.3。 - Bharath Karnam
7个回答

10

不幸的是,在我看来,MongoDB的Java支持存在问题。

话虽如此,在mongo-java-driver中有一个@deprecated类可以使用:

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

我正在使用这个方法从一个 Document 对象生成 fasterxml(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>

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


1
我使用 String id = ObjectId.get().toHexString(); 而不是直接存储 ObjectId - Shadow Man

3
不,无法生成纯粹的JSON。请参考链接
然而,它可以以两种模式生成JSON。
1)严格模式 - 输出您已经获得的内容
2)Shell模式
Shell模式:
JsonWriterSettings writerSettings = new JsonWriterSettings(JsonMode.SHELL, true);           
System.out.println(doc.toJson(writerSettings));

输出:

"createdOn" : ISODate("2016-07-16T16:26:51.951Z")

MongoDB扩展JSON


但是如何将这个 "createdOn" : ISODate("2016-07-16T16:26:51.951Z") 转换为 Date() 呢? - Bharath Karnam

2
理论上我们应该使用toJSON()来序列化对象,但是在实际操作中,至少在3.6版本之前,toJSON()并不支持一些旧的JSON.serialize()方法所支持的类型,比如由aggregate()输出的AggregateIterable<Document>对象。更多信息请参见:https://jira.mongodb.org/browse/JAVA-1770

2
以下是2020年更新,确切回答您的问题,即获取此确切格式:
"modified":"2016-07-16T16:26:51.951Z"

您需要像notionquest建议的那样使用writerSettings,但要使用自定义日期转换器和DateTimeFormatter.ISO_INSTANT。
public class JsonDateTimeConverter implements Converter<Long> {

    private static final Logger LOGGER = LoggerFactory.getLogger(JsonDateTimeConverter.class);
    static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ISO_INSTANT
        .withZone(ZoneId.of("UTC"));

    @Override
    public void convert(Long value, StrictJsonWriter writer) {
        try {
            Instant instant = new Date(value).toInstant();
            String s = DATE_TIME_FORMATTER.format(instant);
            writer.writeString(s);
        } catch (Exception e) {
            LOGGER.error(String.format("Fail to convert offset %d to JSON date", value), e);
        }
    }
}

像这样使用它:
doc.toJson(JsonWriterSettings
            .builder()
            .dateTimeConverter(new JsonDateTimeConverter())
            .build())

1
如果 bson.jar 版本大于 3.0.0,您可以尝试使用 document.toJson()。

0
尝试这个:
final JsonWriterSettings settings = JsonWriterSettings.builder( ).outputMode( JsonMode.SHELL ).build( );

System.out.println(doc.toJson(settings));

如果需要的话,您可以更改JsonMode


0

我使用了以下

try {

            MongoDatabase db = mongoClient.getDatabase("dbname");

            MongoCollection<Document> collection = db.getCollection("nameofcollect");

            Gson gson = new Gson();

            ArrayList<JsonObject> array = new ArrayList<JsonObject>();


            String jsonString = null;
            /*WARNING Gson lib serialize string ->means add slash if you convert "json string" into "json string"*/
            for (Document doc : collection.find()) {
                 jsonString = gson.toJson(doc);              
                 array.add(new Gson().fromJson(jsonString, JsonObject.class));
            }

            //String finalarry = gson.toJson(array);

            Map<Object, ArrayList<JsonObject>> seedMap = new HashMap<Object, ArrayList<JsonObject>>();
            // String encode = coCoRy.encryptAndEncode(jsonString);
            seedMap.put("seed", array);     
            String seedJsonString = gson.toJson(seedMap);

            mongoClient.close();

            return seedJsonString;


        } catch (MongoException | ClassCastException e) {
            e.printStackTrace();
            return null;
        }

结果将会像下面这样

{
    "seed": [
        {
            "_id": {
                "timestamp": 1590914828,
                "counter": 10457170,
                "randomValue1": 5587428,
                "randomValue2": -25784
            },
            "FIR_EVID_NUM": "3436345346",
            "FIR_REG_NUM": "89678967",
            "LOGIN_ID": "pc_admin",
            "MEDIA_PATH": "C:\\Users\\ALPHAMALE\\Documents\\ShareX\\Screenshots\\2020-05\\1590211570.png"
        },
        {
            "_id": {
                "timestamp": 1590924463,
                "counter": 7254997,
                "randomValue1": 5012578,
                "randomValue2": 24700
            },
            "FIR_EVID_NUM": "999999",
            "FIR_REG_NUM": "888888",
            "LOGIN_ID": "32323",
            "MEDIA_PATH": "C:/uploads/c46847c7e2d130ffd746c789c0f0932e.png"
        }
    ]
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接