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?
Use the JavaScript function JSON.stringify() to convert it into a string. const myJSON = JSON.stringify(obj); The result will be a string following the JSON notation.
A JSONObject constructor can be used to convert an external form JSON text into an internal form whose values can be retrieved with the get and opt methods, or to convert values into a JSON text using the put and toString methods.
A JSONObject is an unordered collection of name/value pairs. Its external form is a string wrapped in curly braces with colons between the names and values, and commas between the values and names.
To access the JSON object in JavaScript, parse it with JSON. parse() , and access it via “.” or “[]”.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With