Jackson Annotations 简明教程
Jackson Annotations - @JsonCreator
@JsonCreator 用于对反序列化中使用的构造方法或工厂方法进行微调。我们将使用@JsonProperty来达到同样的目的。在下面的示例中,我们通过定义必需的属性名称将具有不同格式的json与我们的类进行匹配。
Example @JsonCreator
import java.io.IOException;
import java.text.ParseException;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonTester {
public static void main(String args[]) throws ParseException{
String json = "{\"id\":1,\"theName\":\"Mark\"}";
ObjectMapper mapper = new ObjectMapper();
try {
Student student = mapper
.readerFor(Student.class)
.readValue(json);
System.out.println(student.rollNo +", " + student.name);
}
catch (IOException e) {
e.printStackTrace();
}
}
}
class Student {
public String name;
public int rollNo;
@JsonCreator
public Student(@JsonProperty("theName") String name, @JsonProperty("id") int rollNo){
this.name = name;
this.rollNo = rollNo;
}
}