- 
                Notifications
    You must be signed in to change notification settings 
- Fork 4
Java GsonBuilder Example
        Ramesh Fadatare edited this page Jul 12, 2019 
        ·
        1 revision
      
    Gson is a Java serialization/deserialization library to convert Java Objects into JSON and back. Gson was created by Google for internal use and later open-sourced.
GsonBuilder builds Gson with various configuration settings. GsonBuilder follows the builder pattern, and it is typically used by first invoking various configuration methods to set desired options, and finally calling create().
This is a Maven dependency for Gson:
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.2</version>
</dependency>In the example, we write an object into JSON. We use GsonBuilder to create Gson.
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.IOException;
import java.io.PrintStream;
class User {
    
    private final String firstName;
    private final String lastName;
    public User(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }
}
public class GsonBuilderEx {
    public static void main(String[] args) throws IOException {
        try (PrintStream prs = new PrintStream(System.out, true, 
                "UTF8")) {
            
            Gson gson = new GsonBuilder()
                    .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
                    .create();
            
            User user = new User("Peter", "Flemming");
            gson.toJson(user, prs);
        }
    }
}Output:
{"FirstName":"Peter","LastName":"Flemming"}