2017-04-11 29 views
1

次のjsonを非直列化してJava pojoにします。デシリアライズ時に空の文字列をnullとして無視します。

[{ 
    "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クラスのようになります。私はジャクソン2.8.6

ObjectMapper.read(json, LIST_OF_SERVER_TYPE_REFERENCE); 

を使用しますが、私は次の例外を取得しておく

public class Server { 

    public Image image; 
    // lots of other attributes 

} 

public class Image { 

    public String url; 
    // few other attributes 

} 

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ように見えるので、私は、カスタムデシリアライザ1に行ってきましたしません:

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; 
関連する問題