Read Large JSON Files Using Gson

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate.

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

Load the whole file in memory and translate each JavaScript object to a Java object containing all the properties, array objects, etc. It is similar to the DOM way to read XML files.

  • 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

cities_json

City and Coord model classes

city_model

coord_model

Now we will read the JSON file from assets folder using stream model

read_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.


References

Advertisements

What Is Android Intent ?

I was reading about Android Intents and I found this explanation very simple.

​An Intent is an “intention” to perform an action; in other words,

a messaging object you can use to request an action from another app component

An Intent is basically a message to say you did or want something to happen. Depending on the intent, apps or the OS might be listening for it and will react accordingly. Think of it as a blast email to a bunch of friends, in which you tell your friend John to do something, or to friends who can do X (“intent filters”), to do X. The other folks will ignore the email, but John (or friends who can do X) will react to it.

To listen for an broadcast intent (like the phone ringing, or an SMS is received), you implement a broadcast receiver, which will be passed the intent. To declare that you can handle another’s app intent like “take picture”, you declare an intent filter in your app’s manifest file.

If you want to fire off an intent to do something, like pop up the dialer, you fire off an intent saying you will.


References