JSONObject to Document

19,233

Solution 1

Just to help you. You can also do:

JSONObject rat = exRat.getJSONObject("fieldfromJson");String newrat = rat.toString();

Then you have to parse the field you want, and you have a string.

Solution 2

The MongoDB Java Driver provides the Document.parse(String json) method to get a Document instance from a JSON string. You will need to parse your JSON object back to a String like this:

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

And here's the docs for working with JSON in the MongoDB Java Driver.

Share:
19,233
user1577708
Author by

user1577708

Updated on June 15, 2022

Comments

  • user1577708
    user1577708 almost 2 years

    Hi there i am new with mongodb and i want to convert JSONObject to Document and then store it to mongodb. Here is what i have coded.I get a service api in json.

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

    then i want to save this Rat to a mongodb as a document and then insert it to mongodb or to mysql so that i can display it later. I thought something like

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

    but how to do the convertion from JSONObject to Document?

    • user1577708
      user1577708 over 8 years
      i have read this link this link and this link
    • user1577708
      user1577708 over 8 years
      I also want to get some values from the Rat . I have already done this. But still thinking how to save JSONObject to mogno only.