John Manko
John Manko

Reputation: 1908

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?

Upvotes: 0

Views: 219

Answers (1)

John Manko
John Manko

Reputation: 1908

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());
    }

}

Upvotes: 1

Related Questions