Java JsonDeserialize-class And Method Code Example
Here is an example of how to use the JsonDeserialize annotation to deserialize JSON to a Java object using the Jackson library:
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Example {
public static void main(String[] args) throws IOException {
String json = "{\"name\":\"John\",\"age\":30}";
ObjectMapper objectMapper = new ObjectMapper();
Person person = objectMapper.readValue(json, Person.class);
System.out.println(person.getName());
System.out.println(person.getAge());
}
public static class Person {
private String name;
private int age;
@JsonDeserialize(using = CustomDateDeserializer.class)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
}
You should also define a custom deserializer that implements JsonDeserializer interface and use @JsonDeserialize(using = CustomDeserializer.class) to apply it to the field you want to deserialize.