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

WordPress Android App with REST API And Retrofit

Retrofit is the library which converts your JSON data into Java object. In this tutorial, we will learn about how to implement the Retrofit to create a WordPress Mobile App. As we all know, WordPress is the one of the biggest CMS (Content Management System) of the world. Wordpress full fill the requirements for all most every type of the website. So, in this tutorial, I am going to learn how to create an Android App using the WordPress REST API and Retrofit. What is Retrofit? If you want to know about Retrofit, I would like to give you just a simple one-line explanation of the Retrofit. It is a library which converts your REST HTTP request to Java interface. We will learn how we can do all these stuff using some very simple steps. Further, you can check the Retrofit Library here . So, In this tutorial, we will use the Retrofit to retrieve all post and there except ( A short Description of Post) form a WordPress website. Prerequisite for using the Retrofit for WordPress Android App Ther

Flutter Theme Creation, Programmatic Way

Flutter and Dart is an excellent combination for creating the mobile app with material design with nice GUI. Its lots of widget which help the developer for creating the app UI very fast with respect to the other language. You may face some problem in starting due to comm, curly brace and semicolon but after some time you will find the way how to work with these all stuff and it becomes very easy for you. But in this article, we are not going to discuss all these. In this article, we will handle a very interesting topic on how to create a custom theme or multiple themes and let's user decide which theme to use. Create a flutter project So let's create a flutter project by selecting the appropriate option from the File menu in android studio or Visual Code. If you are new to Flutter and Dart you can check out our recent post to get started Creating Cross-platform app using flutter . Once your project is created you will get the default counter app and you try running the app in

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 sy