gson spring code example

Example: gson spring boot

pom.xml

    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.8.5</version>
    </dependency>
    
In your class 

toJson() – Convert Java objects to JSON
	Gson gson = new Gson();
    
    // 1. Java object to JSON file
    Staff obj = new Staff();
    gson.toJson(obj, new FileWriter("C:\\projects\\staff.json"));
    
    // 2. Java object to JSON string
    String jsonInString = gson.toJson(obj);
    
fromJson() – Convert JSON to Java objects

	Gson gson = new Gson();

    // 1. JSON file to Java object
    Staff staff = gson.fromJson(new FileReader("C:\\projects\\staff.json"), Staff.class);

    // 2. JSON string to Java object
    String json = "{'name' : 'mkyong'}";
    Staff staff = gson.fromJson(json, Staff.class);
        
    // 3. JSON file to JsonElement, later String
    JsonElement json = gson.fromJson(new FileReader("C:\\projects\\staff.json"), JsonElement.class);
    String result = gson.toJson(json);

Tags:

Misc Example