You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot中@RequestBody如何将空字符串转为Long类型的0值

Spring Boot @RequestBody接收JSON时空字符串转Long类型0的实现方案

方案一:全局配置Jackson反序列化规则(全项目Long类型统一生效)

该方案适合项目中所有Long类型字段遇到空字符串都需要转为0的场景,一次配置全局生效。

  1. 自定义Long类型反序列化器
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import java.io.IOException;

public class EmptyStringToLongDeserializer extends StdDeserializer<Long> {

    public EmptyStringToLongDeserializer() {
        super(Long.class);
    }

    @Override
    public Long deserialize(JsonParser parser, DeserializationContext context) throws IOException {
        String value = parser.getText().trim();
        // 空/空白字符串直接返回0
        if (value.isEmpty()) {
            return 0L;
        }
        try {
            return Long.parseLong(value);
        } catch (NumberFormatException e) {
            // 非数字格式可按需返回0或抛出异常,此处按需求返回0
            return 0L;
        }
    }
}
  1. 注册反序列化器到Spring Boot全局Jackson配置
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class JacksonCustomConfig {
    @Bean
    public Jackson2ObjectMapperBuilderCustomizer addCustomLongDeserializer() {
        return builder -> builder.deserializerByType(Long.class, new EmptyStringToLongDeserializer());
    }
}

方案二:指定字段单独配置反序列化规则(仅生效于目标字段)

该方案适合仅个别字段需要空字符串转0的场景,不会影响其他Long类型字段的反序列化逻辑。
在对应实体类的目标字段上添加@JsonDeserialize注解,指定使用自定义的反序列化器即可:

import com.fasterxml.jackson.databind.annotation.JsonDeserialize;

public class Page{
  private Long id;
  // 仅该字段使用自定义反序列化规则
  @JsonDeserialize(using = EmptyStringToLongDeserializer.class)
  private Long parentId;
  //  getter、setter省略
}

注:复用方案一中编写的EmptyStringToLongDeserializer即可

方案三:Setter方法手动处理(无额外配置,灵活度最高)

无需新增额外配置类,直接修改对应实体类的Setter方法实现转换逻辑:

public class Page{
  private Long id;
  private Long parentId;

  // 适配字符串入参的Setter,Jackson会自动匹配调用
  public void setParentId(String parentIdStr) {
      if (parentIdStr == null || parentIdStr.trim().isEmpty()) {
          this.parentId = 0L;
      } else {
          this.parentId = Long.parseLong(parentIdStr.trim());
      }
  }

  public Long getParentId() {
      return parentId;
  }
  // 其他getter、setter省略
}

内容的提问来源于stack exchange,提问作者J.Wang

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 05:24:05