BSON to JSON conversion using MongoDB Driver Java API

前端 未结 2 1528
粉色の甜心
粉色の甜心 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}
    
    0 讨论(0)
  • 2020-12-31 22:19

    Natalja's answer is excellent, but if you are using the Mongo Java driver 3.8.2 upwards you will notice some deprecation warnings. If you want the output to look like the input you can use RELAXED JsonWriterSettings mode.

    Below you can see an example with the possible modes and how the JSON will looks like. There are also some deprecation warnings and alternatives to the deprecated code:

    String input = "{ \"timestamp\" : 1486064586641 }";
    org.bson.Document doc = org.bson.Document.parse(input);
    System.out.println("input  = " + input);
    JsonWriterSettings shellMode = JsonWriterSettings.builder().outputMode(JsonMode.SHELL).build();
    System.out.println("output (SHELL) = " + doc.toJson(shellMode));
    JsonWriterSettings strictMode = JsonWriterSettings.builder().outputMode(JsonMode.STRICT).build();
    System.out.println("output (STRICT) = " + doc.toJson(strictMode)); // deprecated - use extended like below
    JsonWriterSettings extendedMode = JsonWriterSettings.builder().outputMode(JsonMode.EXTENDED).build();
    System.out.println("output (EXTENDED) = " + doc.toJson(extendedMode));
    JsonWriterSettings relaxed = JsonWriterSettings.builder().outputMode(JsonMode.RELAXED).build();
    System.out.println("output (RELAXED) = " + doc.toJson(relaxed));
    
    System.out.println("output (JSON) = " + com.mongodb.util.JSON.serialize(doc)); // deprecated - use relaxed like above    
    

    Also note that the JsonWriterSettings constructor is deprecated and you can use as an alternative the builder method like e.g:

    JsonWriterSettings.builder().outputMode(JsonMode.SHELL).build()
    
    0 讨论(0)
提交回复
热议问题