
JS
使用 Bson 将 JSON 转换为 List
Javaimport org.bson.Document;import org.JSon.JSONArray;import org.JSon.JSONObject;import Java.util.ArrayList;import Java.util.List;public class JSonToBsonExample { public static void mAIn(String[] args) { String JSonString = "{\"name\": \"John\", \"age\": 30, \"city\": \"New York\"}"; JSONObject JSonObject = new JSONObject(JSonString); Document document = Document.parse(JSonObject.toString()); List<Document> documents = new ArrayList<>(); documents.add(document); // 打印 List<Document> System.out.println(documents); }}在上面的代码中,我们首先定义了一个 JSON 字符串 JSonString,然后使用 JSONObject 将其转换为 JSON 对象 JSonObject。接下来,我们使用 Document 类的 parse 方法将 JSON 对象转换为 Document 对象,并将其添加到 List[{name=John, age=30, city=New York}]。将 ListJavaimport org.bson.Document;import org.JSon.JSONArray;import Java.util.ArrayList;import Java.util.List;public class BsonToJSonExample { public static void mAIn(String[] args) { List<Document> documents = new ArrayList<>(); Document document1 = new Document("name", "John").append("age", 30).append("city", "New York"); Document document2 = new Document("name", "Jane").append("age", 25).append("city", "London"); documents.add(document1); documents.add(document2); JSONArray JSonArray = new JSONArray(); for (Document document : documents) { JSonArray.put(document.toJSon()); } // 打印 JSON System.out.println(JSonArray.toString()); }}在上面的代码中,我们首先定义了一个 Listdocuments,然后创建了两个 Document 对象 document1 和 document2,并将它们添加到 List 中。接下来,我们使用 JSONArray 将 List[{name=John, age=30, city=New York}, {name=Jane, age=25, city=London}]。通过使用 Bson,我们可以方便地将 JSON 转换为 ListCopyright © 2025 IZhiDa.com All Rights Reserved.
知答 版权所有 粤ICP备2023042255号