如果您只想对少数String 字段执行此操作,请先创建一个自定义JsonDeserializer:
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
public class EmptyToNullCustomDeserializer extends JsonDeserializer<String> {
@Override
public String deserialize(JsonParser jp, DeserializationContext dc) throws IOException, JsonProcessingException {
JsonNode node = jp.readValueAsTree();
if (node.textValue().isEmpty()) {
return null;
}
return node.textValue();
}
}
然后在POJO的每个String上添加这个注解:@JsonDeserialize(using = EmptyToNullCustomDeserializer.class)。
例如:
@JsonDeserialize(using = EmptyToNullCustomDeserializer.class)
private String content;
编辑:
如果您有很多 String 字段要进行预处理,那么对每个字段进行注释可能会非常麻烦。
作为替代方案,您可以对 all String 字段进行预处理,而无需对其进行注释。为此,您必须首先修改EmptyToNullCustomDeserializer,使其父类为Jacksons StdDeserializer:
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import java.io.IOException;
import org.springframework.stereotype.Component;
@Component
public class EmptyToNullCustomDeserializer extends StdDeserializer<String> {
protected EmptyToNullCustomDeserializer() {
super(String.class);
}
@Override
public String deserialize(JsonParser jp, DeserializationContext dc) throws IOException, JsonProcessingException {
JsonNode node = jp.readValueAsTree();
if (node.textValue().isEmpty()) {
return null;
}
return node.textValue();
}
}
然后通过将上述反序列化器添加到配置中来创建此组件以自定义 Jackson 对象映射器:
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.NonNull;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.stereotype.Component;
@Component
public class JacksonConfiguration {
@Autowired
private EmptyToNullCustomDeserializer emptyToNullCustomDeserializer;
@Primary
@Bean
public Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder(List<Jackson2ObjectMapperBuilderCustomizer> customizers) {
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
for (Jackson2ObjectMapperBuilderCustomizer customizer : customizers) {
customizer.customize(builder);
}
return builder;
}
@Bean
public Jackson2ObjectMapperBuilderCustomizer addEmptyToNullStringDeserialization() {
return new Jackson2ObjectMapperBuilderCustomizer() {
@Override
public void customize(Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder) {
jacksonObjectMapperBuilder.deserializerByType(String.class, emptyToNullCustomDeserializer);
}
};
}
}