Skip to main content

How to Read and Write JSON data using GSON

JSON stand for JavaScript Object Notation. In today's development world online application design is not possible without the skills of the JSON. Every application need to read and write the data into JSON format. So, here in this tutorial we are going to learn about " How to Read and Write JSON data using GSON"

Here JSON means we need to add com.google.code.gson:gson:2.8.0 as dependency in our application build.gradle file. So before starting this tutorial you should create a Simple Project with name of "JSON Tutorial" or any other name you per your preference.

For more advanced use of JSON, read below tutorial:-



JSON Basic Element


A JSON object contain many part. Here is the details about how data are stored into the JSON file.

JSON Array([)


In a JSON file , a square bracket ([) represents a JSON array, we can retrieve the JSON array using the below method.
JSONArray jsonarray=response.getJSONArray("keyValue");

JSON Objects({)


In a JSON file, curly bracket ({) represents a JSON object, we can retrieve a JSON Object using the below method.
JSONObject response=obj.getJSONObject("keyObject");

JSON Key


A JSON object has a key that is just a string. A Value of key/value pair create a JSON objects, In above example "keyObject" is the key.

JSON Value


Every key has a value that could be string , integer, Json Object, Json Array or double e.t.c. In above two example we have fetch the JSON object and JSON array using the key. Below is the sample code to fetch the String.
String value=Obj.getString("key");

Sample JSON file


Below is a sample JSON file which we will created in this tutorial and parse the same JSON file and it is required by below Post.java as well.
{ "postHeading": "How to Read and Write JSON data using GSON", 
"postUrl": "http://www.nplix.com",
"postAuthor": "Pawan Kumar",
"postTag":
[
"Android",
"Json", "Angular",
"AndroidStudio"
]
}

Post.java


First of all we need to create a class to store the JSON data. Which we will use to automatically store the json data into files and vice versa.
package com.nplix.jsontutorial;

import java.util.List;

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

public class Post {
private String postHeading;
private String postUrl;
private String postAuthor;
private List<String> postTag;

public Post() {
super();
}

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

public String getPostHeading() {
return postHeading;
}

public void setPostHeading(String postHeading) {
this.postHeading = postHeading;
}

public String getPostUrl() {
return postUrl;
}

public void setPostUrl(String postUrl) {
this.postUrl = postUrl;
}

public String getPostAuthor() {
return postAuthor;
}

public void setPostAuthor(String postAuthor) {
this.postAuthor = postAuthor;
}

public List<String> getPostTag() {
return postTag;
}

public void setPostTag(List<String> postTag) {
this.postTag = postTag;
}
}

Prepare the MainActivity.java file as given below and initialize the some basic variable and method which we are going to use in our code.

Variable Initialization for JSON Tutorial


private TextView textView;
private StringBuilder stringBuilder;

In our Activity onCreate method add below line, you might get some error as we call two method here which are yet not created in our MainActivity.java.
setContentView(R.layout.activity_main);
textView=findViewById(R.id.textView);

// Get the file Location and name where Json File are get stored
String fileName=getCacheDir()+"PostJson.json";

//call write Json method
writeJSONtoFile(fileName);

//Read the written Json File
readJSONfromFile(fileName);

Write JSON data to file


Create a method which will write the Json data to file and later we will use the same file while we are reading the JSON from file.
private void writeJSONtoFile(String s) {

//Create list to store the all Tags
List<String> tags=new ArrayList<String>();
// Add the Tag to List
tags.add("Android");
tags.add("Angular");

//Create a Object of Post
Post post=new Post("Json Tutorial","www.nplix.com","Pawan Kumar",tags);

//Create a Object of Gson
Gson gson=new Gson();

//Convert the Json object to JsonString
String jsonString=gson.toJson(post);

//Initialize the File Writer
FileWriter fileWriter= null;
try {
fileWriter = new FileWriter(s);
} catch (IOException e) {
e.printStackTrace();
}
//write the json string to file
try {
fileWriter.write(jsonString);
} catch (IOException e) {
e.printStackTrace();
}
//Close the File
try {
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}

In below code we will create a list to store the all Tags.
List<String> tags=new ArrayList<String>();
tags.add("Android");
tags.add("Angular");

In this part of the code we are creating the object of Post class.
 Post post=new Post("Json Tutorial","www.nplix.com","Pawan Kumar",tags);

Create an Object of Gson
 Gson gson=new Gson();

Convert the Json object to JsonString
 String jsonString=gson.toJson(post);

Here in below code we will write the Json data to file.
FileWriter fileWriter= null;
try {
fileWriter = new FileWriter(s);
} catch (IOException e) {
e.printStackTrace();
}

So now write the json string to file.
try {
fileWriter.write(jsonString);
} catch (IOException e) {
e.printStackTrace();
}

Reading the data from JSON file


We have create the above method to write the JSON data into the file. It will store the file into cache memory. We are storing the files into the cache memory, so that system can release this automatically when system run out of space.

Now in the below method we are using the same file for reading and converting them to JSON format. Below code is self-explanatory along with comment.
private void readJSONfromFile(String s) {
//Creating a new Gson object to read data
Gson gson=new Gson();
//Read the PostJSON.json file
try {
BufferedReader bufferedReader = new BufferedReader(
new FileReader(s));
//Convert the Json File to Gson Object
Post post=gson.fromJson(bufferedReader,Post.class);
//Initialize the String Builder
stringBuilder=new StringBuilder("Post Details\n---------------------");
stringBuilder.append("\nPost Heading: "+post.getPostHeading());
stringBuilder.append("\nPost URL: "+post.getPostUrl());
stringBuilder.append("\nPost Author: "+post.getPostAuthor());
stringBuilder.append("\nTAGS");

//get the all Tags
for(String Tag:post.getPostTag()){
stringBuilder.append(Tag+",");
}

//Display the all Json object in text View
textView.setText(stringBuilder.toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}


Note:


Reading and Writing the Json data into file is very easy, only most important thing is that we should have same variable name in Gson file as given sample JSON file at start of tutorial and variable name in Post.java file.

Other Post of JSON and REST:-

 

Comments

  1. […] 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“. […]

    ReplyDelete

Post a Comment

Popular posts from this blog

Flutter How to Start Android Activity from Flutter View

Flutter and Dart is an excellent combination for creating the UI, but for accessing the platform-specific service we need to open platform-specific activity. So lets in this article we will explore how to start an android activity and access the service from Flutter View. Create a Project for this Android Activity Flutter View Demo Create a Project From File menu select the New Flutter Project Enter the project name Select the AndroidX support and click on next After the above, we step click on Finish We will have the following project structure created. Create the Second Activity in Android Just go to the android folder and open it in separate windows. We will have the following project structure. Create the Activity Just right-click on the Kotlin folder and create a blank activity from the menu. If you create the activity then you may be required to upgrade the Gradle and do some import. So Just click on update and wait for the project s

Kotlin Parcelable Array Objects Send To Activity

We know that IPC (Inter Process Communication) between the activity is an extremely important part of any application development. We often required that we need to send some data to other activity. For example, we may be required to send an array of data, data could be an Integer, String, Long, Double, Float or any other custom data objects. So, In this example, we are going to learn how to implement the Kotlin Parcelable Array object to send the data from one activity to second activity. What is Parcel? The parcel class is designed as a high-performance IPC transport. A Parcel can contain both flattened data that will be unflattened on the other side of the IPC, and references to live IBinde r objects that will result in the other side receiving a proxy IBinder connected with the original IBinder in the Parcel. Create Kotlin Parcelable Array Objects Parcelable is API for placing the arbitrary objects into the Parcel. In Actual in android app development, Parcelable is an interface

Create Custom EditText View in Android

We use the EditText for taking the input from the user and use it at several places in our project. We required to do lots of customization for each time and there are lots of redundant code we write. Writing and managing these redundant codes is very difficult for example if we want to change the look and feel of the view them we need to modify it at each place where our EditText is getting used. So to avoid these kinds of the problem we can create our own Custom EditText View by just. The EditText view is just an extension of the TextView with lots of editing option and properties that required for the user input. How To Create Custom EditText View For creating the Custom EditText we need to extend the AppCompatEditText and override all three constructors of the view as given below. import android.content.Context; import android.graphics.Typeface; import android.support.annotation.Nullable; import android.support.v7.widget.AppCompatEditText; import android.util.AttributeSet; public