简体   繁体   English

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

[英]Mongo Java: How to serialize DBObject as JSON on file?

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 所有keyvalue对是类型的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序列DBObject JSON文件?

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

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM