【问题标题】:Convert any attribute from org.bson.Document to JSON将任何属性从 org.bson.Document 转换为 JSON
【发布时间】:2015-11-30 04:41:31
【问题描述】:

我有 org.bson.Document 对象,我需要检索一些属性并将它们转换为 JSON(字符串)。

public String example(Document doc){
    Object obj = doc.get("key");
    // the object can be a string, long, document, arrayList...
    // I need to return a JSON String
    return obj.toString();
}

有没有不使用“实例”的简单方法来实现这一点? “get”的结果是一个对象,可以是 ArrayList、String、Long、Document……

编辑:到目前为止,我取得的最好成绩是这样的......

public String example(Document doc){
    Object obj = new JSONObject(doc.toJson()).opt("key");
    return obj!=null ? obj.toString():"";
}

它有效,但我认为它有一些开销,有没有更好的方法?

谢谢 ;-)

【问题讨论】:

    标签: java json mongodb object instance


    【解决方案1】:

    这是将 Document 转换为 JSONObject 的方法:

    Document doc = ...;
    JSONObject object = new JSONObject(doc.get("key", Map.class));
    

    然后就可以得到字符串了:

    object.toJSONString()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-26
      • 2016-09-21
      • 2016-08-09
      • 1970-01-01
      • 2023-03-16
      • 2020-10-19
      相关资源
      最近更新 更多