BSON to JSON conversion using MongoDB Driver Java API

前端 未结 2 1546
粉色の甜心
粉色の甜心 2020-12-31 21:32

I am using MongoDB Driver Java API to convert BSON to JSON. I have test code like this.

String input = \"{ \\\"timestamp\\\" : 1486064586641 }\";
org.bson.Do         


        
2条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-31 21:57

    BSON Documnet's toJson method supports only output to MongoDB Extended JSON (STRICT or SHELL format). If you want to have regular JSON, you can use com.mongodb.util.JSON class:

    String input = "{ \"timestamp\" : 1486064586641 }";
    org.bson.Document doc = org.bson.Document.parse(input);
    System.out.println("input  = " + input);
    System.out.println("output (SHELL) = " + doc.toJson(new JsonWriterSettings(JsonMode.SHELL)));
    System.out.println("output (STRICT) = " + doc.toJson(new JsonWriterSettings(JsonMode.STRICT)));
    System.out.println("output (JSON) = " + com.mongodb.util.JSON.serialize(doc));
    

    This will generate following output:

    input  = { "timestamp" : 1486064586641 }
    output (SHELL) = { "timestamp" : NumberLong("1486064586641") }
    output (STRICT) = { "timestamp" : { "$numberLong" : "1486064586641" } }
    output (JSON) = { "timestamp" : 1486064586641}
    

提交回复
热议问题