Android org.json

| Page Views: 174

This involves tutorials and examples involving using the native JSONObject and JSONArray classes.

Here we see examples involving generating and processing JSON data using JSONObject and JSONArray which do reside in the org.json package.


Android JSONArray Tutorial and Examples

JSONArray is a class representing a dense indexed sequence of values.

For these mapping names have to be unique and non-null strings.

On the hand values may be any mix of :

  1. JSONObjects
  2. JSONArrays
  3. Strings
  4. Booleans
  5. Integers
  6. Longs
  7. Doubles
  8. NULL
  9. null.

Values may not be NaNs, infinities, or of any type not listed above.

Null and null, beware are different.

Instances of JSONArray class are not thread safe. Moreover, JSONArray should not be subclassed as it was not designed for inheritance.

Let's start by introdution to JSON

Quick JSONArray Examples

1. How to load JSON From Assets Folder into a List

We will load the JSON from our assets folder into an InputStream, which we read into a byte[] and then close.

Then later we turn that byte array into a string and return it.

  private String loadJSONFromAsset() {
    String json;
    try {
      InputStream is = getAssets().open("quotes.json");
      int size = is.available();
      byte[] buffer = new byte;
      //noinspection ResultOfMethodCallIgnored;
      json = new String(buffer, "UTF-8");
    } catch (IOException ex) {
      Log.e(TAG, "loadJSONFromAsset", ex);
      return null;
    return json;

Then now we can use that loadJSONFromAsset() method. This time around our aim is to return a List of quotes.

We will first start by instantiating the JSONArray, passing in the loadJSONFromAsset() method, which will be returning a json string.

Then we will be looping through our JSONArray, obtaining JSONObjects in the process and extracting properties which we pass to our quote constructor as we instantiate the Quote.

We then fill our List collection. We are doing these for every iteration. Here's the full method:

  private List<Quote> getQuotes() {
    try {
      JSONArray array = new JSONArray(loadJSONFromAsset());
      List<Quote> quotes = new ArrayList<>();
      for (int i = 0; i < array.length(); i++) {
        JSONObject branchObject = array.getJSONObject(i);
        String quote = branchObject.getString("quote");
        String author = branchObject.getString("author");
        quotes.add(new Quote(author, quote));
      return quotes;
    } catch (JSONException e) {
      Log.e(TAG, "getJSONFromAsset", e);
    return null;
2. How to turn a JSONArray into a Collection

Let's say you are receiving a JSONArray from somewhere and you want it turned into a collection of objects.

Well we can create a toCollection() method. First we will instantiate that Collection as an ArrayList.

Then loop through the JSONArray. For every iteration we will check if the current entry is an instance of JSONObject. If so we add it to our collection.

On the other hand if it is a JSONArray we recursively call this toCollection() method.

If it is a primitive type on the other hand we simply add it to our collection.

  public static Collection<Object> toCollection(JSONArray array) {
    Collection<Object> collection = new ArrayList<>();

    for (int i = 0; i < array.length(); i++) {
        Object entry = array.get(i);

        if (entry instanceof JSONObject) {
            collection.add(toMap((JSONObject) entry));
        } else if (entry instanceof JSONArray) {
            collection.add(toCollection((JSONArray) entry));
        } else {

    return collection;


Android JSONObject Tutorial and Examples

JSONObject is a class representing a modifiable set of name/value mappings.

For these mapping names have to be unique and non-null strings.

On the hand values may be any mix of :

  1. JSONObjects
  2. JSONArrays
  3. Strings
  4. Booleans
  5. Integers
  6. Longs
  7. Doubles or
  8. NULL.

Values may not be null, NaNs, infinities, or of any type not listed above.

Take note that NULL is different from null. Continue reading to check difference.

NULL vs null

NULL is an Object representing a sentinel value used to explicitly define a name with no value.

The difference with null is that values with NULL:

  1. show up in the names() array.
  2. show up in the keys() iterator
  3. return true for has(String)
  4. do not throw on get(String)
  5. are included in the encoded JSON string.

This value violates the general contract of equals(Object) by returning true when compared to null. Its toString() method returns null.

Quick JSONObject Examples

Let's look at some quick JSON examples.

1. How to Generate JSON using JSONObject

JSONObject remember, we said is a class representing a modifiable set of name/value mappings.

Let's say we want to create a class responsing for creating us JSON data.

First step is to import the classes we want to use:

import org.json.JSONException;
import org.json.JSONObject;

In this case we've imported JSONObject and JSONException, both from the org.json package.

Then as an instance field we instantiate the JSONObject:

    private JSONObject object = new JSONObject();

Then creat a method that will receive a name String and a value object and put them in our JSONObject instance.

To put them we simply use the put() method. Then we you invoke the public gen() of the class instance we simply return you our JSONObject instance.

import org.json.JSONException;
import org.json.JSONObject;

public class JsonGenerator {

    private JSONObject object = new JSONObject();

    public JsonGenerator put(String name, Object value){
        JSONObject tmpObj = object;
        try {
        } catch (JSONException e) {
            object = tmpObj;
        return this;

    public JSONObject gen() {
        return object;
2. JSONObject Example

Here's another JSONObject example

import org.json.JSONObject;

public class MrHelloWorld { 

    public static void main(String[] args) {
        // convert Java to json 
        JSONObject root = new JSONObject();
        root.put("message", "Hello");
        JSONObject place = new JSONObject();
        place.put("name", "World!");
        root.put("place", place);
        String json = root.toString();

        // convert json to Java 
        JSONObject jsonObject = new JSONObject(json);
        String message = jsonObject.getString("message");
        String name = jsonObject.getJSONObject("place").getString("name");
        System.out.println(message + " " + name);

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section.

About Me.

After completing his Software Engineering bachelors program, Oclemy(Clement Ochieng) these days is a man of two lives. At day he works for a startup in Nairobi, Kenya. At night he works tirelessly on building ProgrammingWizards TV, a tv channel for student coders and this website to help share the source code. In between he practices Meditation and Self actualization to help him keep balance. He also likes going for long solo walks to connect more with nature.


What do You Think

Previous Post Next Post