2017-11-25 15 views
2

나는 Car 기본 클래스 및지도 문자열을 가져야한다지도, 자동차의 서브 클래스)잭슨 역 직렬화 목록

때문에 내 자신의 사용자 정의

@Override 
public Map<String, Car<?, ?>> deserialize(JsonParser p, DeserializationContext ctxt) 
     throws IOException, JsonProcessingException { 

    JsonNode carsNode = p.getCodec().readTree(p); 
    Map<String, Car<?, ?>> CarsMap = new HashMap<String, Car<?, ?>>(); 
    ObjectMapper mapper = new ObjectMapper(); 

    for (JsonNode node : carsNode) { 
     CarsMap.put(node.get("name").asText(), mapper.readValue(node.asText(), Car.class)); 
    } 
    return CarsMap; 
} 

생각 디시리얼라이저이 작동하지 않습니다이

입력 JSON = { "이름": "혼다", "타입"의 "정규"속도 "(60)}]

이 맵에 있어야 같은

+0

나는 왜 당신이 자동차의 목록으로 deserialize하지 않는지 궁금해하고, 별도의 메소드/클래스를 map으로 변환하는 이유는 무엇일까요? – Pulkownik

+0

@Pulkownik 저는 실제로 자동차를 deserializng하는 데 어려움을 겪고 있습니다. "mapper.readValue (node.asText(), Car.class)"이 doen't는 작동합니다. – user3100209

+0

자동차 클래스가 어떻게 생겼는지 보여줍니다. @JsonDeserialize를 사용합니까? – Pulkownik

답변

0

Car 클래스에 주석을 달아 JSON의 "type" 필드에 따라 인스턴스화 할 하위 클래스를 Jackson에게 알릴 수 있습니다. 예를 들어, RegularCarClassicCar이 있고 Car 인 경우

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, 
    property = "type") 
@JsonSubTypes({ 
    @JsonSubTypes.Type(value = RegularCar.class, name = "Regular"), 
    @JsonSubTypes.Type(value = ClassicCar.class, name = "Classic") 
}) 
class Car { 

이이 같은 구문 분석 할 수있는 것 : Car car 실제로 RegularCar 예를 가리키는

String json = "{\"name\": \"honda\", \"type\": \"Regular , \"speed\": 60}"; 
Car car = mapper.readValue(json, Car.class); 

. 컨테이너는 Map<String, Car<?, ?>> CarsMap으로 선언되었으므로 여기 정확히 put을 입력하고 getMap에서 적절하게 전송하면됩니다.

+0

주석없이이 작업을 수행하고 싶습니다. 그 이유는 Jackson과 밀접하게 결합되어 있기 때문입니다. – user3100209