MongoDB团队是否表示Java驱动程序是否支持javax.json classes?我找不到任何提及,赞成或反对。如果没有,是否有一个已知的库来处理翻译,或者我应该只写一个?
答案 0 :(得分:0)
对于快速而肮脏的转换,也许是这样的事情:
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());
}
}