简体   繁体   中英

MongoDB and JSONP (javax.json)

Has the MongoDB team expressed whether or not the Java driver will support the javax.json classes ? I can't find any mention of it, in favor or against. If not, is there a known library to handle the translation, or should I just write one?

Perhaps something like this for a quick and dirty conversion:

import com.mongodb.DBObject;
import com.mongodb.util.JSON;
import java.io.StringReader;
import java.io.StringWriter;
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonWriter;

public class MongoDBTranslator {

    public static JsonObject convertDocumentToJson(org.bson.Document bson) {
        JsonObject obj = null;
        try (StringReader sReader = new StringReader(bson.toJson());
                javax.json.JsonReader reader = Json.createReader(sReader)) {
            obj = reader.readObject();
            reader.close();
        }
        return obj;
    }

    public static DBObject convertJsonToDocument(JsonObject json) {
        StringWriter sw = new StringWriter();
        try (JsonWriter writer = Json.createWriter(sw)) {
            writer.writeObject(json);
            writer.close();
        } catch (Exception ex) {
            //error
            return null;
        }      

        return (DBObject) JSON.parse(sw.toString());
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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