Java 中 Json 的 Bson 文档
Bson Document to Json in Java
这是我的代码:
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());
}
}
}
这是 toJson
的输出:
"modified" : { "$date" : 1475789185087}
这是我 toString
的输出:
{"modified":"Fri Oct 07 02:56:25 IST 2016"}
我想要 Json 中的字符串日期格式,怎么办?
不,不可能生成普通的 JSON。请参考这个 link.
但是,它可以在两种模式下产生JSON。
1) 严格模式 - 你已经得到的输出
2) Shell 模式
Shell 模式:-
JsonWriterSettings writerSettings = new JsonWriterSettings(JsonMode.SHELL, true);
System.out.println(doc.toJson(writerSettings));
输出:-
"createdOn" : ISODate("2016-07-16T16:26:51.951Z")
可悲的是,IMO,MongoDB Java 支持已损坏。
也就是说,mongo-java-驱动程序中有一个 @deprecated
class,您可以使用:
String json = com.mongodb.util.JSON.serialize(document);
System.out.println("JSON serialized Document: " + json);
我正在使用它从我可以通过 new ObjectMapper().readValue(json, MyObject.class)
.
反序列化的 Document
对象生成 fasterxml (jackson) 兼容 JSON
但是,由于 JSON
class 已弃用,我不确定他们希望您使用什么。不过暂时还在项目中(截至v3.4.2)
我正在我的 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>
我使用异步驱动程序实际获取和推送更新 mongo,非异步驱动程序仅用于 JSON.serialize
方法。
理论上我们应该使用 toJSON()
每...
https://jira.mongodb.org/browse/JAVA-1770
但是,似乎至少在 3.6 之前,toJSON()
不支持旧的 JSON.serialize()
方法处理的各种类型,例如 AggregateIterable<Document>
对象由 aggregate()
.
输出
这是 2020 年的更新,可以准确回答您的问题,即获取此确切格式:
"modified":"2016-07-16T16:26:51.951Z"
您必须使用建议的 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);
}
}
}
这样使用:
doc.toJson(JsonWriterSettings
.builder()
.dateTimeConverter(new JsonDateTimeConverter())
.build())
我使用了以下
try {
MongoDatabase db = mongoClient.getDatabase("dbname");
MongoCollection<Document> collection = db.getCollection("nameofcollect");
Gson gson = new Gson();
ArrayList<JsonObject> array = new ArrayList<JsonObject>();
String jsonString = null;
/*WARNING Gson lib serialize string ->means add slash if you convert "json string" into "json string"*/
for (Document doc : collection.find()) {
jsonString = gson.toJson(doc);
array.add(new Gson().fromJson(jsonString, JsonObject.class));
}
//String finalarry = gson.toJson(array);
Map<Object, ArrayList<JsonObject>> seedMap = new HashMap<Object, ArrayList<JsonObject>>();
// String encode = coCoRy.encryptAndEncode(jsonString);
seedMap.put("seed", array);
String seedJsonString = gson.toJson(seedMap);
mongoClient.close();
return seedJsonString;
} catch (MongoException | ClassCastException e) {
e.printStackTrace();
return null;
}
结果如下
{
"seed": [
{
"_id": {
"timestamp": 1590914828,
"counter": 10457170,
"randomValue1": 5587428,
"randomValue2": -25784
},
"FIR_EVID_NUM": "3436345346",
"FIR_REG_NUM": "89678967",
"LOGIN_ID": "pc_admin",
"MEDIA_PATH": "C:\Users\ALPHAMALE\Documents\ShareX\Screenshots\2020-05\1590211570.png"
},
{
"_id": {
"timestamp": 1590924463,
"counter": 7254997,
"randomValue1": 5012578,
"randomValue2": 24700
},
"FIR_EVID_NUM": "999999",
"FIR_REG_NUM": "888888",
"LOGIN_ID": "32323",
"MEDIA_PATH": "C:/uploads/c46847c7e2d130ffd746c789c0f0932e.png"
}
]
}
试试这个:
final JsonWriterSettings settings = JsonWriterSettings.builder( ).outputMode( JsonMode.SHELL ).build( );
System.out.println(doc.toJson(settings));
您可以根据需要更改 JsonMode
这是我的代码:
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());
}
}
}
这是 toJson
的输出:
"modified" : { "$date" : 1475789185087}
这是我 toString
的输出:
{"modified":"Fri Oct 07 02:56:25 IST 2016"}
我想要 Json 中的字符串日期格式,怎么办?
不,不可能生成普通的 JSON。请参考这个 link.
但是,它可以在两种模式下产生JSON。
1) 严格模式 - 你已经得到的输出
2) Shell 模式
Shell 模式:-
JsonWriterSettings writerSettings = new JsonWriterSettings(JsonMode.SHELL, true);
System.out.println(doc.toJson(writerSettings));
输出:-
"createdOn" : ISODate("2016-07-16T16:26:51.951Z")
可悲的是,IMO,MongoDB Java 支持已损坏。
也就是说,mongo-java-驱动程序中有一个 @deprecated
class,您可以使用:
String json = com.mongodb.util.JSON.serialize(document);
System.out.println("JSON serialized Document: " + json);
我正在使用它从我可以通过 new ObjectMapper().readValue(json, MyObject.class)
.
Document
对象生成 fasterxml (jackson) 兼容 JSON
但是,由于 JSON
class 已弃用,我不确定他们希望您使用什么。不过暂时还在项目中(截至v3.4.2)
我正在我的 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>
我使用异步驱动程序实际获取和推送更新 mongo,非异步驱动程序仅用于 JSON.serialize
方法。
理论上我们应该使用 toJSON()
每...
https://jira.mongodb.org/browse/JAVA-1770
但是,似乎至少在 3.6 之前,toJSON()
不支持旧的 JSON.serialize()
方法处理的各种类型,例如 AggregateIterable<Document>
对象由 aggregate()
.
这是 2020 年的更新,可以准确回答您的问题,即获取此确切格式:
"modified":"2016-07-16T16:26:51.951Z"
您必须使用建议的 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);
}
}
}
这样使用:
doc.toJson(JsonWriterSettings
.builder()
.dateTimeConverter(new JsonDateTimeConverter())
.build())
我使用了以下
try {
MongoDatabase db = mongoClient.getDatabase("dbname");
MongoCollection<Document> collection = db.getCollection("nameofcollect");
Gson gson = new Gson();
ArrayList<JsonObject> array = new ArrayList<JsonObject>();
String jsonString = null;
/*WARNING Gson lib serialize string ->means add slash if you convert "json string" into "json string"*/
for (Document doc : collection.find()) {
jsonString = gson.toJson(doc);
array.add(new Gson().fromJson(jsonString, JsonObject.class));
}
//String finalarry = gson.toJson(array);
Map<Object, ArrayList<JsonObject>> seedMap = new HashMap<Object, ArrayList<JsonObject>>();
// String encode = coCoRy.encryptAndEncode(jsonString);
seedMap.put("seed", array);
String seedJsonString = gson.toJson(seedMap);
mongoClient.close();
return seedJsonString;
} catch (MongoException | ClassCastException e) {
e.printStackTrace();
return null;
}
结果如下
{
"seed": [
{
"_id": {
"timestamp": 1590914828,
"counter": 10457170,
"randomValue1": 5587428,
"randomValue2": -25784
},
"FIR_EVID_NUM": "3436345346",
"FIR_REG_NUM": "89678967",
"LOGIN_ID": "pc_admin",
"MEDIA_PATH": "C:\Users\ALPHAMALE\Documents\ShareX\Screenshots\2020-05\1590211570.png"
},
{
"_id": {
"timestamp": 1590924463,
"counter": 7254997,
"randomValue1": 5012578,
"randomValue2": 24700
},
"FIR_EVID_NUM": "999999",
"FIR_REG_NUM": "888888",
"LOGIN_ID": "32323",
"MEDIA_PATH": "C:/uploads/c46847c7e2d130ffd746c789c0f0932e.png"
}
]
}
试试这个:
final JsonWriterSettings settings = JsonWriterSettings.builder( ).outputMode( JsonMode.SHELL ).build( );
System.out.println(doc.toJson(settings));
您可以根据需要更改 JsonMode