曹耘豪的博客

Jackson

  1. 常用Deserializer
    1. 将空字符串为null
    2. 将object反序列化为String

常用Deserializer

将空字符串为null

EmptyStringNullDeserializer.java
1
2
3
4
5
6
7
8
9
10
11
12
public class EmptyStringNullDeserializer extends JsonDeserializer<String> {
@Override
public String deserialize(JsonParser jsonParser, DeserializationContext ctxt) throws IOException, JsonProcessingException {
JsonNode node = jsonParser.readValueAsTree();
// 不用考虑null的情况
String text = node.asText();
if (text.isEmpty()) {
return null;
}
return text;
}
}

将object反序列化为String

针对json里为object,但反序列的对象的字段为String

1
2
3
4
5
6
7
8
9
10
11
12
public class RawJsonDeserializer extends JsonDeserializer<String> {
@Override
public String deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
// 获取该段json的开始和结束
int begin = (int) p.getCurrentLocation().getCharOffset();
p.skipChildren();
int end = (int) p.getCurrentLocation().getCharOffset();
// 这里是完整的json字符串,所以截取即可
String json = p.getCurrentLocation().getSourceRef().toString();
return json.substring(begin - 1, end);
}
}
   / 
,更新于