Mongo Java:如何在文件中将DBObject序列化为JSON?

时间:2021-10-07 12:36:07

I have a document in MongoDB as

我在MongoDB中有一个文件

name: name
date_created: date
p_vars: {
   01: {
      a: a,
      b: b,
   }
   02: {
      a: a,
      b: b,
   }
   ....
}

represented as DBObject

表示为DBObject

  • All key, value pairs are of type String
  • 所有键值对都是String类型

  • I want to serialize this document using Java, Looking at the api, I did not find anything, How can I serialize a DBObject as JSON on file?
  • 我想用Java序列化这个文档,看看api,我什么都没找到,怎么能把DBObject序列化为JSON文件?

3 个解决方案

#1


12  

It seems that BasicDBObject's toString() method returns the JSON serialization of the object.

似乎BasicDBObject的toString()方法返回对象的JSON序列化。

#2


3  

Looks like the JSON class has a method to serialize objects into JSON (as well as to go the other way and parse JSON to retrieve a DBObject).

看起来JSON类有一个方法将对象序列化为JSON(以及另一种方式并解析JSON以检索DBObject)。

#3


2  

I used the combination of BasicDBObject's toString() and GSON library in the order to get pretty-printed JSON:

我按顺序使用BasicDBObject的toString()和GSON库的组合来获得漂亮的JSON:

    com.mongodb.DBObject obj = new com.mongodb.BasicDBObject();
    obj.put("_id", ObjectId.get());
    obj.put("name", "name");
    obj.put("code", "code");
    obj.put("createdAt", new Date());

    com.google.gson.Gson gson = new com.google.gson.GsonBuilder().setPrettyPrinting().create();

    System.out.println(gson.toJson(gson.fromJson(obj.toString(), Map.class)));

#1


12  

It seems that BasicDBObject's toString() method returns the JSON serialization of the object.

似乎BasicDBObject的toString()方法返回对象的JSON序列化。

#2


3  

Looks like the JSON class has a method to serialize objects into JSON (as well as to go the other way and parse JSON to retrieve a DBObject).

看起来JSON类有一个方法将对象序列化为JSON(以及另一种方式并解析JSON以检索DBObject)。

#3


2  

I used the combination of BasicDBObject's toString() and GSON library in the order to get pretty-printed JSON:

我按顺序使用BasicDBObject的toString()和GSON库的组合来获得漂亮的JSON:

    com.mongodb.DBObject obj = new com.mongodb.BasicDBObject();
    obj.put("_id", ObjectId.get());
    obj.put("name", "name");
    obj.put("code", "code");
    obj.put("createdAt", new Date());

    com.google.gson.Gson gson = new com.google.gson.GsonBuilder().setPrettyPrinting().create();

    System.out.println(gson.toJson(gson.fromJson(obj.toString(), Map.class)));