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

时间:2017-04-11 15:19:59

标签: 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)
}]

我的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 ('')

如果我为它添加一个String setter

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 个答案:

答案 0 :(得分: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;