@JsonDeserialize 주석 JSON을 Java 객체로 역직렬화하는 동안 사용자 정의 역직렬화를 선언하는 데 사용됩니다. StdDeserializer 를 확장하여 사용자 정의 역직렬 변환기를 구현할 수 있습니다. 일반 유형이 Employee 인 클래스 deserialize()를 재정의해야 합니다. StdDeserializer 메소드 수업.
구문
@Target(value={ANNOTATION_TYPE,METHOD,FIELD,TYPE,PARAMETER})
@Retention(value=RUNTIME)
public @interface JsonDeserialize 아래 프로그램에서 @JsonDeserialize 를 사용하여 사용자 지정 deserializer를 구현할 수 있습니다. 주석
예시
import java.io.*;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.annotation.*;
import com.fasterxml.jackson.databind.deser.std.*;
public class JsonDeSerializeAnnotationTest {
public static void main (String[] args) throws JsonProcessingException, IOException {
Employee emp = new Employee(115, "Adithya");
ObjectMapper mapper = new ObjectMapper();
String jsonString = mapper.writeValueAsString(emp);
emp = mapper.readValue(jsonString, Employee.class);
System.out.println(emp);
}
}
// CustomDeserializer class
class CustomDeserializer extends StdDeserializer<Employee> {
public CustomDeserializer(Class<Employee> t) {
super(t);
}
public CustomDeserializer() {
this(Employee.class);
}
@Override
public Employee deserialize(JsonParser jp, DeserializationContext dc) throws IOException, JsonProcessingException {
int id = 0;
String name = null;
JsonToken currentToken = null;
while((currentToken = jp.nextValue()) != null) {
switch(currentToken) {
case VALUE_NUMBER_INT:
if(jp.getCurrentName().equals("id")) {
id = jp.getIntValue();
}
break;
case VALUE_STRING:
switch(jp.getCurrentName()) {
case "name":
name = jp.getText();
break;
default:
break;
}
break;
default:
break;
}
}
return new Employee(id, name);
}
}
// Employee class
@JsonDeserialize(using=CustomDeserializer.class)
class Employee {
private int id;
private String name;
public Employee(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("ID: ").append(this.id).append("\nName: ").append(this.name);
return sb.toString();
}
} 출력
ID: 115 Name: Adithya