EN
Java - parse JSON to object with Jackson lib
5 points
In this short article, we would like to show how to convert JSON to Java object, using 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
String userJson = "{\"name\":\"John\",\"age\":21}"; // {"name":"John","age":21}
7
User userObject = objectMapper.readValue(userJson, User.class);
8
9
System.out.println(userObject.getName()); // John
10
System.out.println(userObject.getAge()); // 21
Hint: to know how to attach
*.jar
lib to out project read this article.
Note: if you want to convert
Object
to JSONString
read this article.
Link to the library in the Maven repository:
https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind
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
String userJson = "{\"name\":\"John\",\"age\":21}";
13
User userObject = objectMapper.readValue(userJson, User.class);
14
15
System.out.println(userObject.getName()); // John
16
System.out.println(userObject.getAge()); // 21
17
}
18
}
Example output:
xxxxxxxxxx
1
John
2
21
User.java
file content:
xxxxxxxxxx
1
package examples;
2
3
public static class User {
4
5
private String name;
6
private int age;
7
8
// required no-arguments constructor
9
public User() {
10
// nothing here ...
11
}
12
13
public String getName() {
14
return this.name;
15
}
16
17
public int getAge() {
18
return this.age;
19
}
20
}