convert ListDocument to json

5

I have a problem I do not know how to convert the List<document> to json:

    public static List<Document> d() {
            conexion c = new conexion();
            List<Document> resultados = new ArrayList<>();
            for (Document cur : c.table.find()){
                resultados.add(cur);
            }      
            return resultados;
        }
    
asked by Kevin Castaño 04.10.2017 в 22:20
source

2 answers

5

There is an easier way according to the mongo documentation here

 public static List<String> d() {
        conexion c = new conexion();
        List<String> resultados = new ArrayList<>();
        for (Document cur : c.table.find()){
            resultados.add(cur.toJson());
//contiene un error en la sintaxis  System.out.println("toda la collection"+.find());
        }      
        return resultados;
    }

so you can directly get a complete list of json's for you to use, with the method toJson() you convert the table objects into json. at the end what you get is a string (" String ") with json

format

as an additional here there is a similar question in English

    
answered by 04.10.2017 / 22:24
source
0

To convert a Document to Json, we use the method toJson () that gets a Json representation of Document

To obtain all the tables in the document, this is done as follows:

    List<String> resultados = new ArrayList<String>();
    for (Document cur : c.table.find()){
        resultados.add(cur.toJson());
    }      

You can also use a BasicDBList to save it and get the Json of the entire collection by JSON.serialize() :

   MongoCursor<Document> iterator = c.table.find().iterator();

    BasicDBList list = new BasicDBList();
    while (iterator.hasNext()) {
        Document doc = iterator.next();
        list.add(doc);
    }
    System.out.println(JSON.serialize(list));
    
answered by 04.10.2017 в 23:47