Spring - Custom deserialization of JSON requests
Spring uses Jackson library to convert JSON requests to Java objects. I’ll talk about customizing JSON request mapping in this post.
Take following JSON as an example request:
{
"name":"Ali",
"birth":1912,
"alive":true
}
Suppose we have following POJO and controller:
public class Person {
private String name;
private int birth;
private boolean alive;
//getters,setters
}
public class PersonController {
@RequestMapping("/save")
public ResponseEntity save(@RequestBody Person person) throws Exception {
//process the Person instance
}
}
The above request is successfully deserialized by Spring and given to handler method. To demonstrate custom deserialization, let’s modify the request protocol:
{
"name":"Ali",
"birth":1912,
"alive":"T"
}
alive
is a string now, but it’s appropriate to provide a boolean to handler,
instead of plain string. Jackson has custom deserializer
support which
allows any valid JSON to be deserialized as desired. We’ll modify Person
class as follows to indicate it should be deserialized in a custom way:
@JsonDeserialize(using = PersonDeserializer.class)
public class Person {
private String name;
private int birth;
private boolean alive;
//getters,setters
}
And we should implement the deserializer:
public class PersonDeserializer extends JsonDeserializer {
@Override
public Object deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
JsonNode node = jsonParser.getCodec().readTree(jsonParser);
String name = node.get("name").textValue();
int birth = node.get("category").intValue();
String aliveStr = node.get("alive").textValue();
return new Person(name, birth, Objects.equals(aliveStr, "T"));
}
}
Jackson library will detect the annotation and use PersonDeserializer
to
parse the requests. Now we have a handler which accepts "T"
as true
.