How to Read and Write JSON data using GSON

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:-

 

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

This Post Has 3 Comments

Leave a Reply

Close Menu