Guide to JSON for Android Developer (Part 1)

Andrea
4 min readSep 27, 2022

--

JavaScript Object Notation, more commonly known as JSON, is an open data interchange format that is both human and machine-readable, as the names says it is a format to represent an object. Despite the name JavaScript Object Notation, JSON is independent of any programming language and is a common API output in a wide variety application.

JSON represents data in two ways:

  • Object : a collection of name-value (or key-value) pairs. An object is defined within left { and right } braces. Each name-value pair begin with the name, followed by a colon, followed by the value. Name-value paired are comma separated.
  • Array : an ordered collection of values. An array is defined within left [ and right ] brackets. Items in the array are comma separated.
  • Keys: Every JSONObject has a key string that’s contains certain value
  • Value: Every key has a single value that can be of any type string, double, integer, boolean etc

JSON file is commonly used in Android application to transfer data from API server. For example API server normally return a response in JSON format, thus parsing JSON format response to Kotlin/Java Object is necessary. Vice versa, API server also accept JSON format data, thus to send it to API server Kotlin/Java Object should be parsed to JSON format.

Android provides four different classes to manipulate JSON data. These classes are JSONArray, JSONObject, JSONStringer and JSONTokenizer.

  1. Parsing simple data from JSON to Object :

Consider this response from movie API that we need to parse it to Movie data class.

{
"Title": "Superman",
"Year": "1978",
"Rated": "PG",
"Released": "15 Dec 1978",
"Runtime": "143 min",
"Genre": "Action, Adventure, Sci-Fi",
"Director": "Richard Donner",
"Writer": "Jerry Siegel, Joe Shuster, Mario Puzo",
"Actors": "Christopher Reeve, Margot Kidder, Gene Hackman",
"Plot": "An alien orphan is sent from his dying planet to Earth, where he grows up to become his adoptive home's first and greatest superhero.",
"Language": "English",
"Country": "United States, United Kingdom, Canada",
"Awards": "Nominated for 3 Oscars. 17 wins & 23 nominations total",
"Poster": "https://m.media-amazon.com/images/M/MV5BMzA0YWMwMTUtMTVhNC00NjRkLWE2ZTgtOWEzNjJhYzNiMTlkXkEyXkFqcGdeQXVyNjc1NTYyMjg@._V1_SX300.jpg",
"Ratings": [
{
"Source": "Internet Movie Database",
"Value": "7.4/10"
},
{
"Source": "Rotten Tomatoes",
"Value": "95%"
},
{
"Source": "Metacritic",
"Value": "81/100"
}
],
}
data class Movie(
var title: String? = null,
var year: String? = null,
var genre: String? = null,
var actor: String? = null,
var ratings: ArrayList<Rating> = arrayListOf()
)

data class Rating(
var source: String? = null,
var value: String? = null
)

To convert JSON String into the movie class, we can use this function

private fun parseJsonToMovie (json: String) : Movie {
//create JSONObject from JSON
val jsonObject = JSONObject(json)
// get the value from key
val _title = jsonObject.getString("Title")
val _year = jsonObject.getString("Year")
val _genre = jsonObject.getString("Genre")
val _actor = jsonObject.getString("Actors")
// get JSON Array if necessary and parsing it into object
val _jsonArrayRating = jsonObject.getJSONArray("Ratings")
val _ratings = arrayListOf<Rating>()
for (i in 0 until jsonArrayRating.length()){
val jsonObjectRating = jsonArrayRating.getJSONObject(i)
val _source = jsonObjectRating.getString("Source")
val _value = jsonObjectRating.getString("Value")
_ratings.add(
Rating(source= _source, value = _value)
)
}

return Movie(
title = _title,
year = _year,
genre = _genre,
actor = _actor,
ratings = _ratings
)
}

The first step to parsing a JSON String, we will create an object of class JSONObject. We can get the value that we need based on the key of each object member using JSONObject.getString(key).

Similarly for JSONArray, we can get the JSONArray using JSONObject.getJSONArray(key). For each member inside JSONArray we can parse it into object using steps mention before.

2. Parsing simple data from JSON to Object using library :

The alternative way rather than writing your own JSON parsing function/class, is to use the open source JSON parsing library. Few library that is common use for Android application is Gson, Jackson, Moshi, Volley, etc.

Bellow is the same parsing function using Gson library

private fun parseJsonToMovie (json: String) : Movie {
val gson = Gson()
return gson.fromJson(json, Movie::class.java)
}

However if your variable name is different with the key name, @SerializedNamed(key) is required on your Object class

data class Movie(
@SerializedName("Title") var title: String? = null,
@SerializedName("Year") var year: String? = null,
@SerializedName("Genre") var genre: String? = null,
@SerializedName("Actors") var actor: String? = null,
@SerializedName("Ratings") var ratings: ArrayList<Rating> = arrayListOf()
)

data class Rating(
@SerializedName("Source") var source: String? = null,
@SerializedName("Value") var value: String? = null
)

The part 1 of this writing will be ended here. Feel free to contact me if there is any more information to be included in this article.

Part 2 : Parsing data from Object to JSON (Serialization)
Part 3 : Create TypeConverter for ROOM Database

--

--

Andrea
Andrea

No responses yet