Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BSON to JSON conversion using MongoDB Driver Java API

Tags:

json

mongodb

bson

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

String input = "{ \"timestamp\" : 1486064586641 }";
org.bson.Document doc = org.bson.Document.parse(input);
System.out.println("input  = " + input);
System.out.println("output = " + doc.toJson());

The output is:

input  = { "timestamp" : 1486064586641 }
output = { "timestamp" : { "$numberLong" : "1486064586641" } }

Is there an easy way to make the output look like the input?

like image 821
ytw Avatar asked Feb 02 '17 20:02

ytw


1 Answers

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}
like image 158
Natalja Olefire Avatar answered Sep 29 '22 17:09

Natalja Olefire