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?

user1577708
  • 169
  • 1
  • 1
  • 13
  • 1
    i have read this [link](http://stackoverflow.com/questions/15282181/how-do-i-convert-a-jsonobject-to-class-object) this [link](http://stackoverflow.com/questions/18501758/jsonobject-to-jsonarray) and this [link](http://stackoverflow.com/questions/9151619/java-iterate-over-jsonobject) – user1577708 Jan 26 '16 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. – user1577708 Jan 26 '16 at 21:04

2 Answers2

20

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.

metame
  • 2,480
  • 1
  • 17
  • 22
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.

metame
  • 2,480
  • 1
  • 17
  • 22
GiorgoCH
  • 194
  • 10