You can try using Jackson annotation
. The Jackson annotation @JsonCreator
is used to tell Jackson that the Java object has a constructor (a "creator") which can match the fields of a JSON object to the fields of the Java object.
Let's consider the following JSON object that we want to deserialize.
{
"name":"Mr.Bond",
"age":"30"
}
You can unmarshall the message by annotating the constructor with @JsonCreator
and using the @JsonProperty
public class UserProfileCreator {
public int age;
public String name;
@JsonCreator
public UserProfileCreator(
@JsonProperty("age") int age,
@JsonProperty("name") String name) {
this.age = age;
this.name = name;
}
}
How will it work?
Let's write a small test program.
@Test
public void deserialize()
throws JsonProcessingException, IOException {
String json = "{"age":30,"name":"Mr.Bond"}";
UserProfileCreator obj = new ObjectMapper().reader(UserProfileCreator.class).readValue(json);
assertEquals("Mr.Bond", obj.name);
}