Bson 文档到 Java 中的 Json
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39923406/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Bson Document to Json in Java
提问by Bharath Karnam
This is my code:
这是我的代码:
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());
}
}
}
This the output of toJson
:
这是输出toJson
:
"modified" : { "$date" : 1475789185087}
This is my output of toString
:
这是我的输出toString
:
{"modified":"Fri Oct 07 02:56:25 IST 2016"}
I want String date format in Json, how to do it?
我想要 Json 中的字符串日期格式,怎么做?
采纳答案by notionquest
No, it is not possible to produce the plain JSON. Please refer this link.
不,无法生成纯 JSON。请参考此链接。
However, it can produce JSON in two modes.
但是,它可以在两种模式下生成 JSON。
1) Strict mode - Output that you have already got
1) 严格模式 - 您已经获得的输出
2) Shell mode
2) 壳模式
Shell Mode:-
外壳模式:-
JsonWriterSettings writerSettings = new JsonWriterSettings(JsonMode.SHELL, true);
System.out.println(doc.toJson(writerSettings));
Output:-
输出:-
"createdOn" : ISODate("2016-07-16T16:26:51.951Z")
回答by Shadow Man
Sadly, IMO, MongoDB Java support is broken.
可悲的是,IMO,MongoDB Java 支持被破坏了。
That said, there is a @deprecated
class in the mongo-java-driver that you can use:
也就是说@deprecated
,您可以使用 mongo-java-driver 中的一个类:
String json = com.mongodb.util.JSON.serialize(document);
System.out.println("JSON serialized Document: " + json);
I'm using this to produce fasterxml (Hymanson) compatible JSON from a Document
object that I can deserialize via new ObjectMapper().readValue(json, MyObject.class)
.
我正在使用它从Document
我可以反序列化的对象生成与 fastxml (Hymanson) 兼容的 JSON new ObjectMapper().readValue(json, MyObject.class)
。
However, I'm not sure what they expect you to use now that the JSON
class is deprecated. But for the time being, it is still in the project (as of v3.4.2).
但是,我不确定他们希望您使用什么,因为JSON
该类已被弃用。但目前,它仍在项目中(从 v3.4.2 开始)。
I'm importing the following in my pom:
我在我的 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>
I'm using the async driver for actually fetching and pushing updates to mongo, and the non-async driver solely for the use of the JSON.serialize
method.
我使用异步驱动程序实际获取和推送更新到 mongo,非异步驱动程序仅用于该JSON.serialize
方法的使用。
回答by Kenneth M. Kolano
In theory we are supposed to use toJSON()
per...
https://jira.mongodb.org/browse/JAVA-1770
理论上我们应该使用toJSON()
每个...
https://jira.mongodb.org/browse/JAVA-1770
However, it seems that, at least up through 3.6, toJSON()
isn't supported on various types the old JSON.serialize()
method handled without issue, such as the AggregateIterable<Document>
objects output by aggregate()
.
然而,似乎是,至少向上穿过3.6,toJSON()
不支持各种类型的老JSON.serialize()
没有问题的处理方法,如AggregateIterable<Document>
通过输出对象aggregate()
。
回答by Benjamin Caure
Here is a 2020 update to answer exactly your question, i.e. getting this exact format:
这是 2020 年的更新,可以准确回答您的问题,即获取此确切格式:
"modified":"2016-07-16T16:26:51.951Z"
You have to use writerSettings like notionquest suggested, but with a custom date converter and DateTimeFormatter.ISO_INSTANT:
您必须使用像 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);
}
}
}
Use it like this:
像这样使用它:
doc.toJson(JsonWriterSettings
.builder()
.dateTimeConverter(new JsonDateTimeConverter())
.build())