Json to pojo kotlin

NPLIX

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
Читайте также:  Goolge Adsense Style Popup

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.

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? = null

constructor() : super() <>

constructor(PostHeading: String, PostUrl: String, PostAuthor: String, tags: List) : 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.

Читайте также:  Java accept license agreement

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()
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.

var post = Post("Json Tutorial", "www.nplix.com", "Pawan Kumar", tags)
var jsonString:String = gson.toJson(post)
val file=File(s)
file.writeText(jsonString)

Complete code to write JSON data in Kotlin

private fun writeJSONtoFile(s:String) //Create list to store the all Tags 
var tags = ArrayList()
// 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.

val bufferedReader: BufferedReader = File(f).bufferedReader()
val inputString = bufferedReader.use
var post = gson.fromJson(inputString, Post::class.java)
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 + ",") >
textView?.setText(stringBuilder.toString())

The complete code of reading JSON data in Kotlin

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()
// 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)
//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)
[ 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

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

Log.d("Read JSON Using gson",jsonString)
"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 link
  • Facebook
  • Twitter
  • Pinterest
  • Email
  • Other Apps

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

IntelliJ IDEA/Android studio plugin: Json to Java, Java records and Kotlin POJO (GSON, Logan Square, Jackson, FastJSON, AutoValue, Moshi, Lombok)

License

robohorse/RoboPOJOGenerator

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Intellij Idea and Android Studio plugin for JSON to POJO transformation.

Generates Java, Java Records and Kotlin POJO files from JSON: GSON, FastJSON, AutoValue (GSON), Logan Square, Jackson, Lombok, empty annotations template. Supports: primitive types, multiple inner JSONArrays.

Keywords: JsonToPojo, Json2Pojo, Kotlin, GSON, FastJSON, AutoValue, Jackson, LoganSquare, Moshi, Parcelable, Lombok, Java records.

get it and install from plugin repository or simply find it in Preferences -> Plugins -> Marketplace -> RoboPOJOGenerator

Select target package -> new -> Generate POJO from JSON

put JSON into window and select target POJO type

Copyright 2016 Vadim Shchenev, and licensed under the MIT license. No attribution is necessary but it’s very much appreciated. Star this project if you like it.

About

IntelliJ IDEA/Android studio plugin: Json to Java, Java records and Kotlin POJO (GSON, Logan Square, Jackson, FastJSON, AutoValue, Moshi, Lombok)

Источник

Оцените статью