在反序列化期间将空字符串忽略为 null

ST-*_*DDT 5 java json jackson json-deserialization

我尝试将以下 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)
}]
Run Code Online (Sandbox Code Playgroud)

我的 Java 类如下所示:

public class Server {

    public Image image;
    // lots of other attributes

}
Run Code Online (Sandbox Code Playgroud)

public class Image {

    public String url;
    // few other attributes

}
Run Code Online (Sandbox Code Playgroud)

我使用杰克逊 2.8.6

ObjectMapper.read(json, LIST_OF_SERVER_TYPE_REFERENCE);
Run Code Online (Sandbox Code Playgroud)

但我不断收到以下异常:

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

如果我为它添加一个字符串设置器

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

public void setImage(String value) {
    // Ignore
}
Run Code Online (Sandbox Code Playgroud)

我收到以下异常

Caused by: com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.String out of START_OBJECT token
Run Code Online (Sandbox Code Playgroud)

无论我(也)是否添加 Image setter,异常都不会改变。

我也试过,@JsonInclude(NOT_EMPTY)但这似乎只影响序列化。

摘要:某些(设计不当的)API 向我发送了一个空字符串 ( "") 而不是,null我必须告诉 Jackson 忽略该错误值。我怎样才能做到这一点?

ST-*_*DDT 5

似乎没有开箱即用的解决方案,所以我选择了自定义解串器:

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);
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

并使用以下代码使用它

@JsonDeserialize(using = ImageDeserializer.class)
@JsonProperty("image")
public Image image;
Run Code Online (Sandbox Code Playgroud)