1. Overview
This tutorial will cover quickly how to set up a Gson example with Maven and Gradle so that you can get started with more useful features of Gson.
2. Gson example with Maven and Gradle
The only one dependency of Gson we will need is com.google.code.gson. So, we will have it in the Maven POM file and Gradle build file as the followings:
2.1. Using Gson with Maven
1 2 3 4 5 6 |
<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.7</version> <scope>compile</scope> </dependency> |
2.2. Using Gson with Gradle
1 2 3 |
dependencies { compile group: 'com.google.code.gson', name: 'gson', version:'2.7' } |
2.3. Gson Examples
2.3.1. Convert primitive types to Json
Here are some examples of converting primitive types to Json.
1 2 3 4 5 6 7 8 9 |
// Initialize a Gson object Gson gson = new Gson(); // convert an integer to json String json = gson.toJson(1); // ==> 1 // convert a string to json json = gson.toJson("hello gson"); // ==> "hello gson" // convert an array to json int[] values = { 1, 3, 5 }; json = gson.toJson(values); // ==> [1,3,5] |
2.3.2. Convert Json string to primitive types
1 2 3 4 5 6 7 8 9 10 |
// Initialize a Gson object Gson gson = new Gson(); // Convert Json string to integer value int age = gson.fromJson("10", int.class); // Convert Json string to boolean value Boolean isMarried = gson.fromJson("false", Boolean.class); // Convert Json back to Java string String message = gson.fromJson("\"hello gson\"", String.class); // Convert Json back to an array of string String[] messages = gson.fromJson("[\"hello\", \"world\"]", String[].class); |
2.3.1. Convert a Java object to Json
Assume that we have a User class as below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
public class User { private int id; private String username; private String email; public User() { } public User(int id, String username, String email) { super(); this.id = id; this.username = username; this.email = email; } // getters and setters are omitted } |
To convert a User object to Json
1 2 3 |
User user = new User(1, "admin", "gson@gmail.com"); Gson gson = new Gson(); json = gson.toJson(user); |
To convert a Json string to a User object
1 2 3 |
String userJson = "{\"id\":1,\"username\":\"admin\",\"email\":\"gson@gmail.com\"}"; user = gson.fromJson(userJson, User.class); |
3. Summary
We just got through how to setup a Gson example with Maven and Gradle. We also got through several basic examples with Gson. We can see that it is very easy and simple to initialize a Gson object and convert Java objects to Json string and vice versa. I’d like to share more about Gson tutorial in future posts.
Below are another related tutorial for your references:
Ignore or Exclude Field in Gson
Gson – Convert A String To JsonObject