Guide to JSON for Android Developer (Part 2)

Andrea
2 min readOct 8, 2022

--

This is the series of JSON lesson that I extracted from my projects. It consists of
Part 1 : Parsing data from Json to Object (deserialization)
Part 2 : Parsing data from Object to JSON (Serialization)
Part 3 : Create TypeConverter for ROOM Database

Serialization is the process of converting an object into a stream of bytes. That object can then be saved to a database or transferred over a network.

  1. Serialize simple object to JSON using Java
    Using similar case from Part 1. If we have Movie object
val movie = Movie(title = "A Beutiful Mind",
year = "2001",
genre = "Drama Romance",
actor = "Russel Crowe, Jennifer Connelly",
ratings = arrayListOf(Rating("Tomato", "4.7"), Rating("IMDB", "4.8"))
)

We can convert Movie object to JSON String using function bellow

private fun toJson(movie: Movie) : String {
val jsonObject = JSONObject()
jsonObject.put("Title", movie.title)
jsonObject.put("Year", movie.year)
jsonObject.put("Genre", movie.genre)
jsonObject.put("Actors", movie.actor)

val jsonArray = JSONArray()
for (rating in movie.ratings){
val jsonObjRating = JSONObject()
jsonObjRating.put("Source", rating.source)
jsonObjRating.put("Value", rating.value)
jsonArray.put(jsonObjRating)
}
jsonObject.put("Ratings", jsonArray)
return jsonObject.toString()
}

The function will printout JSON String

{
"Title": "A Beutiful Mind",
"Year": "2001",
"Genre": "Drama Romance",
"Actors": "Russel Crowe, Jennifer Connelly",
"Ratings": [
{
"Source": "Tomato",
"Value": "4.7"
},
{
"Source": "IMDB",
"Value": "4.8"
}
]
}

2. Parsing simple Object to JSON :
Similar with part 1, we can simplify our method by using popular JSON library such as Gson, Jackson, Moshi, Volley, etc.

For example, using Gson library, our function will be :

private fun toJson(movie: Movie) : String {
val gson = GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
.create()
return gson.toJson(movie)
}

In this case because variable name from Movie data class is not identical with JSON key, we must put FieldNamingPolicy.UPPER_CAMEL_CASE. If we have identical variable name data class with JSON key, we can simplify the function further

private fun toJson(movie: Movie) : String {
return Gson().toJson(movie)
}

Another example if we are using Jackson, the function will be :

private fun toJson(movie: Movie) : String {
val mapper = jacksonObjectMapper()
.setPropertyNamingStrategy(PropertyNamingStrategy.UPPER_CAMEL_CASE)
return mapper.writeValueAsString(movie)
}

For Part 3 we will analyse some case where complex object parsing to JSON or vice versa. Thank you

--

--

Andrea
Andrea

No responses yet