0

I'm trying to write/read a json object to/from a file. The json structure is complex and is dynamically generated.

For small json object I would just transform json to string then do string writing/reading. This causes out of memory issue when the json gets too large.

How do I stream the JSONObject directly to a file, and stream back the JSONObject directly from the file?

yongsunCN
  • 736
  • 7
  • 18

2 Answers2

0

Having a quick look at the Android api, it seems that you want functionality similar to JsonStringer (https://developer.android.com/reference/org/json/JSONStringer.html) - but it doesn't seem like it is capable of streaming the results. Other than that, I think you'll be bound to either finding a suitable library (possibily https://github.com/yonik/noggit) or implementing your own json streamer (which I doubt would be that hard).

Warrick
  • 1,623
  • 1
  • 17
  • 20
0

I suggest you use GSON, Google's library to handle JSONs. I use it a lot for converting JSON web responses into classes.

https://github.com/google/gson/blob/master/UserGuide.md

Chisko
  • 3,092
  • 6
  • 27
  • 45
  • 1
    I was going to suggest this as well, but you beat me to it. I'd add that gson can use streams to avoid the memory issues the OP is worried about. – Dan Harms Jun 21 '16 at 22:31
  • Well, I'm trying to stream a json object directly to a file, instead of to a class instance. My json data has complex structure that is not known. If gson can do that, I'd like to ask for a simple sample code to demonstrate this functionality – yongsunCN Jun 21 '16 at 22:54
  • see here http://stackoverflow.com/questions/29965764/how-to-parse-json-file-with-gson and here https://gist.github.com/madonnelly/1371597 for possible choices – Chisko Jun 21 '16 at 23:10