我有像
这样的JSON字符串{"firstName":"ABC", "middleName":"", "lastName":"XYX"}
我正在将此字符串转换为JsonNode
ObjectMapper mapper = new ObjectMapper();
mapper.readValue(jsonString, new TypeReference<JsonNode>() {});
它完美无缺,但我想将中间名值从""
转换为null
,以便JsonNode
应该像
{"firstName":"ABC", "middleName":null, "lastName":"XYX"}
我添加了一个序列化程序
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addSerializer(String.class, new StdSerializer<String>(String.class) {
@Override
public void serialize(String value, JsonGenerator jgen, SerializerProvider provider)
throws IOException, JsonGenerationException {
if("".equalsIgnoreCase(value)){
jgen.writeNull();
}else{
jgen.writeString(value);
}
}
});
mapper.registerModule(module);
mapper.readValue(jsonString, new TypeReference<JsonNode>() {});
但它返回的字符串与JsonNode
相同。我实际上缺少什么?
答案 0 :(得分:0)
杰克逊会为其他对象提供null,但对于Strings,它会给出空字符串。
但您可以使用Custom JsonDeserializer来执行此操作:
class CustomDeserializer extends JsonDeserializer<String> {
@Override
public String deserialize(JsonParser jsonParser, DeserializationContext context) throws IOException, JsonProcessingException {
JsonNode node = jsonParser.readValueAsTree();
if (node.asText().isEmpty()) {
return null;
}
return node.toString();
}
}