JSON exists everywhere and used mainly in REST APIs, There are many ways to read JSON files but here I will cover the two ways that are supported by Gson library.
- Object Model
- Stream Model
Operate on a JSON document as a sequence of tokens that are traversed in depth-first order. Because stream mode reads one token at a time it requires less memory. It is similar to Pull Parsers way to read XML files.
When to use each model depends on your needs, If your JSON file is small then using object model to load the whole file into memory at once will be best choice, But if your JSON file it too large then using stream model will be the best.
I was having a large JSON file (≈ 30 MB) that I wanted to read. I couldn’t read the whole file at once using object model because loading all this data into memory made the system crash, So here I will describe how to use GSON library to read this file using stream model.
Firstly, Let’s take a look how the JSON file formed
City and Coord model classes
Now we will read the JSON file from assets folder using stream model
With this approach we are loading objects one by one, and each time we convert the object that has been read to City model object.
- http://www.acuriousanimal.com/2015/10/23/reading-json-file-in-stream-mode-with-gson.html (This covers reading using object model and stream model)