Search code examples
javajava-8bson

converting byte array into List<? extends Document> (org.bson.Document) using java8


error : The method insertIntoDB(List) in the type InsertIntoDB is not applicable for the arguments (List)


    import java.io.UnsupportedEncodingException;
import java.util.List;
import org.json.JSONObject;
import org.bson.Document;
public class ReadJSONExample{
public static void main(String[] args) throws UnsupportedEncodingException {
JSONObject obj = new JSONObject();
    obj.put("name", "foo");
    obj.put("num", 100);
    obj.put("balance", 1000.21);
    obj.put("is_vip", true);
    obj.put("nickname","hi");
byte[] objAsBytes = obj.toString().getBytes();
    Document doc = convertByteIntoDocument(objAsBytes);
    List<? extends Document> doc2 = (List<? extends Document>) doc;
    ReadJSONExample.insertIntoDB(doc2);
}
private static Document convertByteIntoDocument(byte[] b) {
    return null;
    //need to implement this logic
}
private static void insertIntoDB(List<? extends Document> message) { 
    // inserting bson Document into DB 
}

}


Solution

  • It's difficult to realise what you really want, but there's a special method to create Document from json:

    private static Document convertByteIntoDocument(byte[] b) {
        return Document.parse(new String(b));
    }
    

    P.S. By the way, List<? extends Document> doc2 = (List<? extends Document>) doc; is going to get ClassCastException.