2017-04-11 145 views
1

我嘗試將以下json反序列化爲java pojo。在反序列化過程中忽略空字符串爲空

[{ 
    "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) 
}] 

我的Java類看起來是這樣的:

public class Server { 

    public Image image; 
    // lots of other attributes 

} 

public class Image { 

    public String url; 
    // few other attributes 

} 

我用傑克遜2.8.6

ObjectMapper.read(json, LIST_OF_SERVER_TYPE_REFERENCE); 

,但我不斷收到以下異常:

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

需要自定義使用解串器首先檢查您是否有圖像對象或字符串,然後將其反序列化。 – JMax

回答

0

似乎沒有成爲一個outof的現成的解決方案,所以我去自定義解串器之一:

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; 
相關問題