컴파일 타임 의존성을 피하려면 런타임에 하위 유형 정보를 ObjectMapper#registerSubTypes 또는 ObjectMapper#registerSubTypes에 등록 할 수 있습니다.
예 :
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.MatcherAssert.assertThat;
import java.io.StringReader;
import java.io.StringWriter;
import org.junit.Test;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonTest2 {
// Assuming this is in base Maven module
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "_type")
public static abstract class Connection {
}
// Assuming this is in different Maven module
@JsonTypeName("FileShareConnection")
public static class FileShareConnection extends Connection {
}
// Assuming this is in different Maven module
@JsonTypeName("HadoopConnection")
public static class HadoopConnection extends Connection {
}
// Assuming both modules are available here.
// or you need to load classes via reflection(or some library)
@Test
public void testUseCustomPolymorphicTypeNameInSerializationOption2() throws Exception {
ObjectMapper mapper = new ObjectMapper();
mapper.registerSubtypes(FileShareConnection.class, HadoopConnection.class);
Connection fileShareConnection = new HadoopConnection();
StringWriter sw = new StringWriter();
mapper.writeValue(sw, fileShareConnection);
Connection value = mapper.readValue(new StringReader(sw.toString()), Connection.class);
assertThat(value, instanceOf(HadoopConnection.class));
}
}
추상 클래스가 서브 타입에 대해 알 필요가 왜 받는다는 순환 종속성을 허용하지 않습니다 알고 내가 지금까지 .. 이해하지 못했다. – Sid
@Type 내부에는 value = FileShareConnection.class가 있는데, 이것은 Json을 POJO로 다형성으로 직렬화 해제하기위한 Jackson의 구문입니다. – cyberjoac