java json to bson_Bson Document to Json in Java

This is my code:

MongoDBSingleton dbSingleton = MongoDBSingleton.getInstance();

MongoDatabase db;

try {

db = dbSingleton.getTestdb();

MongoIterable mg = db.listCollectionNames();

MongoCursor iterator=mg.iterator();

while (iterator.hasNext()) {

MongoCollection table = db.getCollection(iterator.next());

for (Document doc: table.find()) {

System.out.println(doc.toJson());

}

}

}

This the output of toJson:

"modified" : { "$date" : 1475789185087}

This is my output of toString:

{"modified":"Fri Oct 07 02:56:25 IST 2016"}

I want String date format in Json, how to do it?

# Answer 1

4d350fd91e33782268f371d7edaa8a76.png

No, it is not possible to produce the plain JSON. Please refer this link.

However, it can produce JSON in two modes.

1) Strict mode - Output that you have already got

2) Shell mode

Shell Mode:-

JsonWriterSettings writerSettings = new JsonWriterSettings(JsonMode.SHELL, true);

System.out.println(doc.toJson(writerSettings));

Output:-

"createdOn" : ISODate("2016-07-16T16:26:51.951Z")

# Answer 2

Sadly, IMO, MongoDB Java support is broken.

That said, there is a @deprecated class in the mongo-java-driver that you can use:

String json = com.mongodb.util.JSON.serialize(document);

System.out.println("JSON serialized Document: " + json);

I'm using this to produce fasterxml (jackson) compatible JSON from a Document object that I can deserialize via 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).

I'm importing the following in my pom:

org.mongodb

mongodb-driver-async

3.4.2

org.mongodb

mongo-java-driver

3.4.2

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.

# Answer 3

In theory we are supposed to use toJSON() per...

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 objects output by aggregate().

# Answer 4

Here is a 2020 update to answer exactly your question, i.e. getting this exact format:

"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:

public class JsonDateTimeConverter implements Converter {

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值