Possible Option: Jackson's ObjectMapper, Using Class or TypeReference
The Direct Answer
ObjectMapper mapper = new ObjectMapper(); // To do the work of serialization/deserialization
String json = "{"
+ "\"name\": \"John\",\n"
+ "\"surname\": \"Doe\"\n"
+ "}";
try {
User user = mapper.readValue(json, User.class); // Deserializing directly to a Class is this easy :)
String msg = String.format("With Class, User's Name: %s, User's Surname: %s", user.getName(), user.getSurname());
System.out.println(msg);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
As a Whole
(Using IntelliJ to easily access the test library)
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.testng.annotations.Test;
public class TestDeserialization {
private ObjectMapper mapper = new ObjectMapper(); // To do the work of serialization/deserialization
private String json = "{"
+ "\"name\": \"John\",\n"
+ "\"surname\": \"Doe\"\n"
+ "}"; // Not a good way to store JSON, but here for demonstration :)
@Test
public void testDeserializationWithClass() {
try {
User user = mapper.readValue(json, User.class); // Deserializing directly to a Class is this easy :)
String msg = String.format("With Class, User's Name: %s, User's Surname: %s", user.getName(), user.getSurname());
System.out.println(msg);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
@Test
public void testDeserializationWithTypeReference() {
try {
/*
TypeReference can handle complexity where the simple Class argument cannot; such as if we needed a Map<String, User>:
Map<String, User> userMap = mapper.readValue(json, new TypeReference<Map<String, User>>() {});
*/
User user = mapper.readValue(json, new TypeReference<User>() {});
String msg = String.format("With TypeReference, User's Name: %s, User's Surname: %s", user.getName(), user.getSurname());
System.out.println(msg);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
}
package test.example;
public class User {
private String name;
private String surname;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
}
Output
With Class, User's Name: John, User's Surname: Doe
With TypeReference, User's Name: John, User's Surname: Doe
References