2016-06-16 2 views
0

가 나는 POJO 계층과 같이이 프로젝트. 내가 직면 한 문제는 각각 다른 Maven 프로젝트 (FileShare 연결은 FileShare maven 프로젝트 안에 있고 Connection은 API maven 프로젝트 안에 있음)에 있습니다.다형성 잭슨 직렬화는

결과적으로 Maven 프로젝트간에 순환 의존성이 있습니다. 추상 클래스는 하위 유형에 대해 알아야하고 하위 유형은 추상 클래스에 대해 알아야합니다.

이 문제를 어떻게 해결할 수 있습니까?

+0

추상 클래스가 서브 타입에 대해 알 필요가 왜 받는다는 순환 종속성을 허용하지 않습니다 알고 내가 지금까지 .. 이해하지 못했다. – Sid

+0

@Type 내부에는 value = FileShareConnection.class가 있는데, 이것은 Json을 POJO로 다형성으로 직렬화 해제하기위한 Jackson의 구문입니다. – cyberjoac

답변

0

컴파일 타임 의존성을 피하려면 런타임에 하위 유형 정보를 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)); 
    } 
}