使用MongoDB驱动程序Java API将BSON转换为JSON [英] BSON to JSON conversion using MongoDB Driver Java API

查看:884
本文介绍了使用MongoDB驱动程序Java API将BSON转换为JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用MongoDB驱动程序Java API将BSON转换为JSON. 我有这样的测试代码.

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());

输出为:

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

有没有一种简单的方法可以使输出看起来像输入?

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

推荐答案

BSON Documnet的toJson方法仅支持输出到 MongoDB扩展JSON (STRICT或SHELL格式).如果要使用常规JSON,可以使用com.mongodb.util.JSON类:

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));

这将产生以下输出:

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

这篇关于使用MongoDB驱动程序Java API将BSON转换为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆