JSONObject for the document

Hi, I am new to mongodb and I want to convert JSONObject to Document and then save it to mongodb. Here is what I encoded. I get 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 in mongodb as a document, and then paste it into mongodb or 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 make a conversion from JSONObject to Document?

+5
source share
2 answers

The MongoDB Java driver provides a Document.parse(String json) method to get an instance of a document from a JSON string. You will need to parse your JSON object back to String as follows:

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

And here are the docs for working with JSON in the MongoDB Java driver.

+8
source

Just to help you. You can also do:

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

Then you need to parse the field you need and you have a string.

+1
source

Source: https://habr.com/ru/post/1241546/


All Articles