10

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?

2
  • 1
    i have read this link this link and this link Commented Jan 26, 2016 at 20:42
  • 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. Commented Jan 26, 2016 at 21:04

2 Answers 2

19

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.