繁体   English   中英

Bson 文档到 Java 中的 Json

[英]Bson Document to Json in Java

这是我的代码:

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 的toJson

"modified" : { "$date" : 1475789185087}

这是我的toString的 output :

{"modified":"Fri Oct 07 02:56:25 IST 2016"}

我想要 Json 中的字符串日期格式,怎么办?

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

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

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

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

但是,由于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方法的使用。

不,无法生成纯 JSON。 请参考此链接

但是,它可以在两种模式下生成 JSON。

1) 严格模式 - 您已经获得的输出

2) 壳模式

外壳模式:-

JsonWriterSettings writerSettings = new JsonWriterSettings(JsonMode.SHELL, true);           
System.out.println(doc.toJson(writerSettings));

输出:-

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

MongoDB 扩展 JSON

理论上我们应该使用toJSON() per... https://jira.mongodb.org/browse/JAVA-1770

但是,似乎至少在 3.6 之前,旧JSON.serialize()方法处理的各种类型都不支持toJSON() ,例如由aggregate()输出的AggregateIterable<Document>对象。

这是 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())

我使用了以下

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"
        }
    ]
}

试试这个:

final JsonWriterSettings settings = JsonWriterSettings.builder( ).outputMode( JsonMode.SHELL ).build( );

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

您可以根据需要更改 JsonMode

如果 bson.jar 版本 > 3.0.0你可以试试document.toJson()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM