使用Jackson将JSON字符串或对象反序列化为String字段
我正在使用Jackson 2库,我正在尝试阅读JSON响应,如下所示:
I am using Jackson 2 library and I am trying to read a JSON response, which looks like:
{ "value":"Hello" }
当值为空时,JSON响应如下:
When value is empty, JSON response looks like:
{ "value":{} }
我的模型POJO类看起来像这样
My model POJO class looks like this
public class Hello {
private String value;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
问题是当响应看起来像{value:{}},杰克逊试图读取一个对象,但我的模型类字段是一个字符串,所以它抛出一个异常:
The problem is that when response looks like {value:{}}, Jackson is trying to read an Object, but my model class field is a string, so it throws an Exception:
JsonMappingException: Can not deserialize instance of java.lang.String out of START_OBJECT token.
我的问题是杰克逊如何成功阅读看起来像的JSON:
My question is how Jackson can successfully read JSONs who look like:
{"value":"something"}
同时如果响应看起来像这个{value:{}}(对我来说是空响应),则将null传递给我的Hello模型类的value字段。
and at the same time if response looks like this {"value":{}} (empty response for me), pass null to value field of my Hello model class.
我使用下面的代码来读取JSON字符串:
I am using the code below in order to read JSON string:
String myJsonAsString = "{...}";
ObjectMapper mapper = new ObjectMapper();
mapper.readValue(myJsonAsString , Hello.class);
您可以为此feld使用自定义反序列化器。如果它在那里则返回一个字符串,或者在任何其他情况下返回null:
You can use a custom deserializer for this feld. Here is one that returns the string if it's there, or null in any other case:
public class Hello {
@JsonDeserialize(using = StupidValueDeserializer.class)
private String value;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
public class StupidValueDeserializer extends JsonDeserializer<String> {
@Override
public String deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
JsonToken jsonToken = p.getCurrentToken();
if (jsonToken == JsonToken.VALUE_STRING) {
return p.getValueAsString();
}
return null;
}
}