2017-04-11 1 views
1

다음 json을 deserialize하여 Java pojo로 변환하려고합니다. 내가비 직렬화 중에 null을 무시합니다.

ObjectMapper.read(json, LIST_OF_SERVER_TYPE_REFERENCE); 

잭슨 2.8.6 사용하지만 나는 다음과 같은 예외가 계속

public class Server { 

    public Image image; 
    // lots of other attributes 

} 

public class Image { 

    public String url; 
    // few other attributes 

} 

을 :

[{ 
    "image" : { 
     "url" : "http://foo.bar" 
    } 
}, { 
    "image" : ""  <-- This is some funky null replacement 
}, { 
    "image" : null <-- This is the expected null value (Never happens in that API for images though) 
}] 

그리고 내 자바 클래스는 다음과 같습니다 :

Caused by: com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of Image: no String-argument constructor/factory method to deserialize from String value ('') 

public void setImage(Image image) { 
    this.image = image; 
} 

public void setImage(String value) { 
    // Ignore 
} 

나는 예외 내가 (도) 이미지 세터를 추가하거나 여부를 변경하지 않습니다

Caused by: com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.String out of START_OBJECT token 

다음과 같은 예외를 얻을 위해 나는 문자열 세터를 추가하는 경우 아니.

나는 또한 @JsonInclude(NOT_EMPTY)을 시도했지만 이것은 직렬화에만 영향을주는 것으로 보입니다.

요약 : 일부 (심하게 설계) API 나에게 빈 문자열 ("")를 보내는 대신 null 난 그냥 나쁜 값을 무시 잭슨에게 있습니다. 어떻게해야합니까?

+1

당신은 사용자 정의를 필요로하는 다음 코드를 사용하여 사용 deserializer는 이미지 객체 또는 문자열이 있는지 먼저 확인한 다음이를 deserialize합니다. – JMax

답변

0

이 박스 솔루션 노출되어 내부 단자부을 것 같다, 그래서 내가 하나 디시리얼라이저 정의에 들어갑니다하지 않습니다

import com.fasterxml.jackson.core.JsonParser; 
import com.fasterxml.jackson.core.JsonProcessingException; 
import com.fasterxml.jackson.core.JsonToken; 
import com.fasterxml.jackson.databind.DeserializationContext; 
import com.fasterxml.jackson.databind.JsonDeserializer; 

import java.io.IOException; 

public class ImageDeserializer extends JsonDeserializer<Image> { 

    @Override 
    public Image deserialize(final JsonParser parser, final DeserializationContext context) 
      throws IOException, JsonProcessingException { 
     final JsonToken type = parser.currentToken(); 
     switch (type) { 
      case VALUE_NULL: 
       return null; 
      case VALUE_STRING: 
       return null; // TODO: Should check whether it is empty 
      case START_OBJECT: 
       return context.readValue(parser, Image.class); 
      default: 
       throw new IllegalArgumentException("Unsupported JsonToken type: " + type); 
     } 
    } 

} 

그리고

@JsonDeserialize(using = ImageDeserializer.class) 
@JsonProperty("image") 
public Image image; 
관련 문제