How to Read and Write JSON data in Kotlin with GSON

Pawan Kumar
NPLIX
Published in
6 min readDec 26, 2017

Kotlin is now official language for Android development and it is well support in Android Studio. So here in this tutorial we are going to learn about how to read and write GSON data in Kotlin. If you would like learn the java version of this tutorial check out the last tutorial “How to Read and Write JSON data using GSON”.

Introduction

In this tutorial we will write two method. In first method we will create a JSON file and in second method we will read the file and and print in a text box. If you like to know more about the basic entity of JSON you can checkout Basic JSON entity here.

JSON file sample for this Kotlin Tutorial

{ "postHeading": "How to Read and Write JSON data using GSON", 
"postUrl": "http://www.nplix.com",
"postAuthor": "Pawan Kumar",
"postTag":
[
"Android",
"Json",
"Angular",
"AndroidStudio"
]
}

Create the POJO class in Kotlin

You must created and implement the POJO class earlier in Java. Here we will create a POJO class in Kotlin as given below.

package com.nplix.jsontutorialkotlin

/**
* Created by PK on 12/24/2017.
*/

class Post {
var postHeading: String? = null
var postUrl: String? = null
var postAuthor: String? = null
var postTag: List<String>? = null

constructor() : super() {}

constructor(PostHeading: String, PostUrl: String, PostAuthor: String, tags: List<String>) : super() {
this.postHeading = PostHeading
this.postUrl = PostUrl
this.postAuthor = PostAuthor
this.postTag = tags
}

}

In above example of POJO class did you notice something? If don’t then let me explain you. In Kotlin we don’t required a Getter and Setter method to set and get the details of the object. Simply you can refer using the variable as like local variable of the class.

post.postHeading

In above example we are just using the postHeading variable using “.” operator. We don’t need to create a method like below to retrieve the value of variable.

public String getPostHeading() {
return postHeading;
}

Write JSON data in Kotlin from file

For writing the JSON data to file in Kotlin, we need to deal with file handling to write the file into file. In this example we are creating the file into cache location. So that it should be get deleted whenever required by system. If you want you create at some different location as well, but make sure to add the appropriate permission to write on storage.

We required a list to store the all tag list as defined in our sample JSON file. So using below code we will create the List of String type in kotlin and add some value into tags List.

var tags = ArrayList<String>()
tags.add("Android")
tags.add("Angular")

Did you know what is difference between var and val in Kotlin? If don’t let me explain you, if you declare a variable as var then value of variable can be change, but if declare as val you can’t change the value later.

Create a Object of Post

var post = Post("Json Tutorial", "www.nplix.com", "Pawan Kumar", tags)

Create a Object of Gson

var gson = Gson()

Convert the Json object to JsonString

var jsonString:String = gson.toJson(post)

Initialize the File Writer and write into file

val file=File(s)
file.writeText(jsonString)

Complete code to write JSON data in Kotlin

Below method will take filename as input and write the JSON data into the file.

private fun writeJSONtoFile(s:String) {
//Create list to store the all Tags
var tags = ArrayList<String>()
// Add the Tag to List
tags.add("Android")
tags.add("Angular")
//Create a Object of Post
var post = Post("Json Tutorial", "www.nplix.com", "Pawan Kumar", tags)
//Create a Object of Gson
var gson = Gson()
//Convert the Json object to JsonString
var jsonString:String = gson.toJson(post)
//Initialize the File Writer and write into file
val file=File(s)
file.writeText(jsonString)
}

Reading JSON data in Kotlin

Reading the data from JSON file is also not so complicated. We have to follow some simple steps for this.

First of all create a local instance of gson using the below code.

var gson = Gson()

Read the PostJSON.json file using buffer reader.

val bufferedReader: BufferedReader = File(f).bufferedReader()

Read the text from buffferReader and store in String variable.

val inputString = bufferedReader.use { it.readText() }

Convert the Json File to Gson Object in Kotlin

var post = gson.fromJson(inputString, Post::class.java)

Store the data in String Builder in kotlin

var post = gson.fromJson(inputString, Post::class.java)
//Initialize the String Builder
stringBuilder = StringBuilder("Post Details\n---------------------")
+Log.d("Kotlin",post.postHeading)
stringBuilder?.append("\nPost Heading: " + post.postHeading)
stringBuilder?.append("\nPost URL: " + post.postUrl)
stringBuilder?.append("\nPost Author: " + post.postAuthor)
stringBuilder?.append("\nTags:")
//get the all Tags using for Each loop
post.postTag?.forEach { tag -> stringBuilder?.append(tag + ",") }

Display the all Json object in text View

textView?.setText(stringBuilder.toString())

Complete code of read JSON data in Kotlin

This method will take the filename as input and display the content in textbox.

private fun readJSONfromFile(f:String) {

//Creating a new Gson object to read data
var gson = Gson()
//Read the PostJSON.json file
val bufferedReader: BufferedReader = File(f).bufferedReader()
// Read the text from buffferReader and store in String variable
val inputString = bufferedReader.use { it.readText() }

//Convert the Json File to Gson Object
var post = gson.fromJson(inputString, Post::class.java)
//Initialize the String Builder
stringBuilder = StringBuilder("Post Details\n---------------------")
+Log.d("Kotlin",post.postHeading)
stringBuilder?.append("\nPost Heading: " + post.postHeading)
stringBuilder?.append("\nPost URL: " + post.postUrl)
stringBuilder?.append("\nPost Author: " + post.postAuthor)
stringBuilder?.append("\nTags:")
//get the all Tags

post.postTag?.forEach { tag -> stringBuilder?.append(tag + ",") }
//Display the all Json object in text View
textView?.setText(stringBuilder.toString())

}

Safe Call in Kotlin

You may have notice that we use “?.” many time in code. In Kotlin it is called Safe Call operator we use this where we think that null value can comes as input or value change to null. So kotlin is well designed to handle the null pointer exception. Check this like to learn more about the Safe Call in Kotlin.

Complete MainActivity.kt

package com.nplix.jsontutorialkotlin

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.TextView
import com.google.gson.Gson
import java.io.*


class MainActivity : AppCompatActivity() {
private var textView: TextView?=null;
private var stringBuilder:StringBuilder?=null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

textView = findViewById(R.id.textView)

// Get the file Location and name where Json File are get stored
val fileName = cacheDir.absolutePath+"/PostJson.json"
//call write Json method
writeJSONtoFile(fileName)
//Read the written Json File
readJSONfromFile(fileName)
}
private fun writeJSONtoFile(s:String) {
//Create list to store the all Tags
var tags = ArrayList<String>()
// Add the Tag to List
tags.add("Android")
tags.add("Angular")
//Create a Object of Post
var post = Post("Json Tutorial", "www.nplix.com", "Pawan Kumar", tags)
//Create a Object of Gson
var gson = Gson()
//Convert the Json object to JsonString
var jsonString:String = gson.toJson(post)
//Initialize the File Writer and write into file
val file=File(s)
file.writeText(jsonString)
}
private fun readJSONfromFile(f:String) {

//Creating a new Gson object to read data
var gson = Gson()
//Read the PostJSON.json file
val bufferedReader: BufferedReader = File(f).bufferedReader()
// Read the text from buffferReader and store in String variable
val inputString = bufferedReader.use { it.readText() }

//Convert the Json File to Gson Object
var post = gson.fromJson(inputString, Post::class.java)
//Initialize the String Builder
stringBuilder = StringBuilder("Post Details\n---------------------")
+Log.d("Kotlin",post.postHeading)
stringBuilder?.append("\nPost Heading: " + post.postHeading)
stringBuilder?.append("\nPost URL: " + post.postUrl)
stringBuilder?.append("\nPost Author: " + post.postAuthor)
stringBuilder?.append("\nTags:")
//get the all Tags

post.postTag?.forEach { tag -> stringBuilder?.append(tag + ",") }
//Display the all Json object in text View
textView?.setText(stringBuilder.toString())

}
}

After you implement this you will get the similar output as given in the screen shots.

Read and Write JSON data in Kotlin

If you have any further query or question then please put your question in the comment section below.

Originally published at NPLIX.

--

--