在反序列化过程中忽略空字符串为空
问题描述:
我尝试将以下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
,我要告诉杰克逊只是忽略坏值。我怎样才能做到这一点?
答
似乎没有成为一个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;
需要自定义使用解串器首先检查您是否有图像对象或字符串,然后将其反序列化。 – JMax