Converting Java object to JSON (GSON)
In this example we will show you how to convert java object to JSON using Gson library. Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object.
Firs of all we need to add following dependency into the maven pom.xml
<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.0</version> </dependency>
So to convert the java object into its JSON representation we need to do following:
Gson gson = new GsonBuilder().create();
String json = gson.toJson(object);
And the full example:
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class ModelToJsonExample {
private static class User {
private String name;
private String emailAddress;
public User(String name, String emailAddress) {
this.name = name;
this.emailAddress = emailAddress;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
}
public static void main(String[] args) {
User user = new User("testName", "testEmailAddress");
Gson gson = new GsonBuilder().create();
String json = gson.toJson(user);
System.out.println(json);
}
}
And the output should be:
{"name":"testName","emailAddress":"testEmailAddress"}