@JsonCreator
标注构造方法或静态工厂方法上 和@JsonProperty或@JacksonInject配合使用
@Test
public void jsonCreator() throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
String jsonStr = "{\"full_name\":\"myName\",\"age\":12}";
TestPOJO testPOJO = objectMapper.readValue(jsonStr,TestPOJO.class);
Assert.assertEquals("myName",testPOJO.getName());
Assert.assertEquals(12, testPOJO.getAge());
}
public static class TestPOJO{
private String name;
private int age;
@JsonCreator
public TestPOJO(@JsonProperty("full_name") String name,@JsonProperty("age") int age){
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
在静态工厂方法上
@Test
public void jsonCreator() throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
String jsonStr = "{\"name\":\"myName\",\"birthday\":1416299461556}";
TestPOJO testPOJO = objectMapper.readValue(jsonStr,TestPOJO.class);
Assert.assertEquals("myName",testPOJO.getName());
System.out.println(testPOJO.getBirthday());
}
public static class TestPOJO{
private String name;
private Date birthday;
private TestPOJO(String name,Date birthday){
this.name = name;
this.birthday = birthday;
}
@JsonCreator
public static TestPOJO getInstance(@JsonProperty("name") String name,@JsonProperty("birthday") long timestamp){
Date date = new Date(timestamp);
return new TestPOJO(name,date);
}
public String getName() {
return name;
}
public Date getBirthday() {
return birthday;
}
}
授权式构造器 比较常用这个构造器只有一个参数
@Test
public void jsonCreator() throws Exception {
ObjectMapper objectMapper = new ObjectMapper();
String jsonStr = "{\"full_name\":\"myName\",\"age\":12}";
TestPOJO testPOJO = objectMapper.readValue(jsonStr,TestPOJO.class);
Assert.assertEquals("myName",testPOJO.getName());
Assert.assertEquals(12,testPOJO.getAge());
}
public static class TestPOJO{
private String name;
private int age;
@JsonCreator
public TestPOJO(Map map){
this.name = (String)map.get("full_name");
this.age = (Integer)map.get("age");
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}