有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java JSONObject到文档

大家好,我是mongodb的新手,我想将JSONObject转换为文档,然后将其存储到mongodb。 以下是我的代码。我得到了一个json格式的服务api

CloseableHttpResponse response = httpClient.execute(get);
        HttpEntity entity = response.getEntity();          
        JSONObject Rat = new JSONObject(EntityUtils.toString(entity));

然后我想将这个Rat作为文档保存到mongodb,然后将其插入mongodb或mysql,以便以后显示。 我觉得

Document  doc = new Document(....);
coll.insertOne(doc); /*where coll is 
MongoCollection<Document> coll = db.getCollection("rates"); */

但是如何实现从JSONObject到Document的转换呢


共 (1) 个答案

  1. # 1 楼答案

    MongoDB Java驱动程序提供了从JSON字符串获取文档实例的Document.parse(String json)方法。您需要将JSON对象解析回如下字符串:

    Document doc = Document.parse( Rat.toString() );
    

    下面是在MongoDB Java驱动程序中使用JSON的docs