EN
Java - convert object to JSON String with Jackson lib
4 points
In this short article, we would like to show how to convert any Java object to JSON, using an external Jackson library.
Quick solution:
xxxxxxxxxx
1
// import com.fasterxml.jackson.core.JsonProcessingException;
2
// import com.fasterxml.jackson.databind.ObjectMapper;
3
4
ObjectMapper objectMapper = new ObjectMapper();
5
6
User userObject = new User("John", 21);
7
String userJson = objectMapper.writeValueAsString(userObject);
8
9
System.out.println(userJson); // {"name":"John","age":21}
Hint: to know how to attach Jackson
*.jar
library to your project read this article.
Note: if you want to parse JSON to
Object
read this article.
Maven repository: https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind
Full example of how to use Jackson library.
Main.java
file content:
xxxxxxxxxx
1
package examples;
2
3
import com.fasterxml.jackson.core.JsonProcessingException;
4
import com.fasterxml.jackson.databind.ObjectMapper;
5
6
public class Main {
7
8
public static void main(String[] arg) throws JsonProcessingException {
9
10
ObjectMapper objectMapper = new ObjectMapper();
11
12
User userObject = new User("John", 21);
13
String userJson = objectMapper.writeValueAsString(userObject);
14
15
System.out.println(userJson); // {"name":"John","age":21}
16
}
17
}
Example output:
xxxxxxxxxx
1
{"name":"John","age":21}
User.java
file content:
xxxxxxxxxx
1
package examples;
2
3
public class User {
4
5
private String name;
6
private int age;
7
8
// it is good to add no-arguments constructor too
9
public User() {
10
// nothing here ...
11
}
12
13
public User(String name, int age) {
14
this.name = name;
15
this.age = age;
16
}
17
18
public String getName() {
19
return this.name;
20
}
21
22
public int getAge() {
23
return this.age;
24
}
25
}