How to Read and Write  JSON data in Kotlin with GSON

How to Read and Write JSON data in Kotlin with GSON

Kotlin is now official language for Android development and it is well supported in Android Studio. So here in this tutorial, we are going to learn about how to read and write JSON data in Kotlin using GSON. If you would like to 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 methods. In the first method, we will create a JSON file and in second method we will read the file and print in a text box.  If you like to know more about the basic entity of JSON you can check out Basic JSON entity here.

What is JSON?

  • JSON stands for JavaScript Object Notation
  • JSON is a lightweight data-interchange format
  • It is “self-describing” and easy to understand
  • JSON is language independent and can we used in any language

JSON Syntax Rules

  • Data is in name/value pairs
  • Data is separated by commas
  • Curly braces hold objects
  • Square brackets hold arrays

JSON data name and value pairs

JSON data written into the name and value pairs. A name and value pairs consist of the filed name (in double quotes ) and value followed by the colon.

"postUrl": "http://www.nplix.com"

JSON value could be a string, number, JSON Object, an array, a boolean or null value.

A JSON file contains the “.json” file extension and MIME type is “application/json”.

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"
 ]
 }

Adding dependency for JSON

To work with JSON into Kotlin we need to add the gson library to our project-level build.gradle file, so includes the below dependency to your project.

implementation 'com.google.code.gson:gson:2.8.1'

Create the POJO class in Kotlin

You must create 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 require 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 the 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 JSON data into the file. In this example, we are creating the file into cache location. So that it should be getting deleted whenever system required disk space. Alternatively,  If you want or depending on the requirement you can create the file 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 to tags List.

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

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

Create an Object of Post

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

Create an 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 the file

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

Complete code to write JSON data in Kotlin

Below method will take a 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())

The complete code of reading JSON data in Kotlin

This method will take the filename as input and display the content in the 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 noticed 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 come 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())

    }
}

So, when you run your application after implementing this you will get the output as given in the screenshots below.

Read and Write JSON data in Kotlin

 

 

Read and Write JSON Object in Kotlin

As I have described at the beginning of this tutorial that a JSON Object is written inside the curly braces. So let’s create another example in which we will read and write the JSON Object in Kotlin.

General properties JSON Object

JSON objects are surrounded by curly braces {}.
JSON objects are written in key/value pairs.
Keys must be strings, and values must be a valid JSON data type (string, number, object, array, boolean or null).
Keys and values of JSON objects are separated by a colon.
Each key/value pair of JSON objects is separated by a comma.

//Create JSON Object in Kotlin
        var jsonObject: JSONObject=JSONObject("name" +":"+ "Pawan Kumar")
        jsonObject.put("website","http://www.nplix.com")
        jsonObject.put("topic","JSON Kotlin Tutorial")
        jsonObject.put("age",5)

Read the data from JSON Object.

//access the JSON Object data in Kotlin

        var name:String= jsonObject.getString("name");
        var website:String=jsonObject.getString("website")
        var topic:String=jsonObject.getString("topic")
        var age:Int=jsonObject.getInt("age")

        Log.d("JSON Data:\n","name:"+name+"\nwebsite:"+website+"\ntopic:"+topic+"\nage:"+age)

The output will look like as given below

[ 03-24 18:58:45.182  3635: 3635 D/JSON Data:
     ]
    name:Pawan Kumar
    website:http://www.nplix.com
    topic:JSON Kotlin Tutorial
    age:5

Reading Data using Gson

To read the data using Gson we need to create an instance of Gson class as given below.

//access JSON data using Gson
        var gson:Gson=Gson()
        var jsonString:String = gson.toJson(jsonObject)

        Log.d("Read JSON Using gson",jsonString)

The output of the above code will be printed into the logs as given below.

{
"nameValuePairs":
{
"topic":"JSON Kotlin Tutorial",
"website":"http://www.nplix.com",
"age":5,
"name":"Pawan Kumar"
}
}

 

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

 

 

Get Email Updates!

Signup now receive an email once I publish new content. I will never give away, trade or sell your email address. You can unsubscribe at any time.

Join 911 other subscribers

Leave a Reply

Close Menu