Skip to content
Related Articles

Related Articles

Java Program to Convert JSON String to JSON Object

View Discussion
Improve Article
Save Article
Like Article
  • Last Updated : 30 Jan, 2022

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.

Example:

Java




// Java Program to demonstrate the 
// conversion of String to JSON object
  
import com.google.gson.*;
  
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);
    }
}


Output:


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!