Android JSONArray


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
      is.read(buffer);
      is.close();
      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 {
            collection.add(entry);
        }
    }

    return collection;
}

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. This feedback helps us gauge our progress.

Help me Grow.

I set myself some growth ambitions I desire to achieve by this year's end regarding this website and my youtube channel. Am halfway. Help me reach them by:




Recommendations


What do You Think


Previous Post Next Post