Convert java object to json (Jackson)
In this example we will show you how to convert java object to JSON using Jackson library.
Firs of all we need to add following dependency into the maven pom.xml
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.8.6</version> </dependency>
To convert the java object into JSON we need to do following:
ObjectMapper objectMapper = new ObjectMapper(); String json = objectMapper.writeValueAsString(object);
And the full example:
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; public class JacksonModelToJsonExample { 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) throws JsonProcessingException { User user = new User("testName", "testEmailAddress"); ObjectMapper objectMapper = new ObjectMapper(); String json = objectMapper.writeValueAsString(user); System.out.println(json); } }
Output should be following:
{"name":"testName","emailAddress":"testEmailAddress"}