Writing out JSON documents using Java

215 views
Skip to first unread message

Jwillis0720

unread,
Jan 13, 2013, 4:23:19 PM1/13/13
to mongod...@googlegroups.com
Hello everyone,

I just "inherited" some code that is written in Java, and I'm trying to write a class to produce a JSON document that outputs to a file so that I may use "mongoimprt' to upload it to my database. There is a nice library in Gson, googles implementation of JSon called JSonWriter that does exactly what I need. Unfortunately, I can't write directly to the db, and need to produce a .json file first, which only affords a 16 mB array of JSON documents that can be uploaded at a time.

I have a complete map class that can should be easy to transfer to a JSON doc but have no way of writing this to a file unless I write my own class to parse through all the docs. There must be something in the library I'm missing.

Please help me! 
j

Jordan Willis

unread,
Jan 13, 2013, 9:39:44 PM1/13/13
to mongod...@googlegroups.com
I think the easiest way to do this was just to turn a map into a JSONObject using https://github.com/douglascrockford/JSON-java/blob/master/JSONObject.java library. And then serialize each object using the toString method thatsalso included. It can then be printed to file using something easy like the PrintWriter Class in java.io 

...
PrintWriter out = new PrintWriter("testprintwriter.json");
JSONObject json_output = JSONObject(my_map)
out.println(json_output.toString())
out.close()
...

The PrintWriter class is a little hokey , but it seems to work just fine. The file produced uploads beautifully into mongoimport.




--
You received this message because you are subscribed to the Google
Groups "mongodb-user" group.
To post to this group, send email to mongod...@googlegroups.com
To unsubscribe from this group, send email to
mongodb-user...@googlegroups.com
See also the IRC channel -- freenode.net#mongodb

Reply all
Reply to author
Forward
0 new messages