Skip to content
Related Articles
Open in App
Not now

Related Articles

Java Program to Convert JSON String to JSON Object

Improve Article
Save Article
  • Difficulty Level : Basic
  • Last Updated : 30 Jan, 2022
Improve Article
Save Article

Gson is a Java library that can be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects whose source code we don’t have. It provides the support to transfer data in between different programming languages modules.

JSON String Representation: The string must be in JSON format which is the name pair value.

jsonString = "{ gfgId : 10001, username : 'Jack jon', gender : 'M' }";

Conversion of JSON String into JSON Object

To convert the above JSON string into an object user must-have class with the same property (same name).

// creating object of Gson
Gson gson = new Gson();

// calling method fromJson and passing JSON string into object

// The first parameter is JSON string

// The second parameter is the Java class to parse the JSON into an instance of.
object = gson.fromJson(jsonString,GFG.class);

For more clarification follow the below example, to convert JSON String into JSON Object.



// Java Program to demonstrate the 
// conversion of String to JSON object
class GFG {
    int gfgId;
    String username;
    char gender;
    public GFG()
        this.gfgId = 0;
        this.username = "";
        this.gender = ' ';
public class GFGMain {
    public static void main(String arg[])
        GFG gfg = null;
        // creating JSON String of GFG class object
        String jsonString;
        jsonString = "{";
        jsonString += "gfgId : 10001,";
        jsonString += "username : 'Jack jon',";
        jsonString += "gender : 'M'";
        jsonString += "}";
        // creating object of gson
        Gson gson = new Gson();
        // converting jsonStrig into object
        gfg = gson.fromJson(jsonString, GFG.class);
        System.out.println("GFG id of User : " + gfg.gfgId);
        System.out.println("Username : " + gfg.username);
        System.out.println("Gender : " + gfg.gender);


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!