Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSONObject to Document

Tags:

java

json

mongodb

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?

like image 239
user1577708 Avatar asked Jan 26 '16 20:01

user1577708


People also ask

Can we convert JSON object to string?

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.

What does JSON object toString do?

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.

What is a JSON object in Java?

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.

How do I access JSON data?

To access the JSON object in JavaScript, parse it with JSON. parse() , and access it via “.” or “[]”.


1 Answers

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.

like image 84
metame Avatar answered Oct 06 '22 00:10

metame