Springboot3+的id字符串转化问题

发布于:2025-06-16 ⋅ 阅读:(21) ⋅ 点赞:(0)

以下是纯后端实现 Long/BigInteger ID 转为 JSON 字符串 的详细配置方案,基于 Spring Boot 3+ 和 SpringDoc (OpenAPI) 最新实践 ✨


1. 添加依赖

确保你的 pom.xml(或 Gradle)中包含:

<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
  <groupId>com.fasterxml.jackson.datatype</groupId>
  <artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
<dependency>
  <groupId>org.springdoc</groupId>
  <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
  <version>2.x</version>
</dependency>

2. 全局 Jackson 配置

创建一个全局 ObjectMapper,让所有 Long 类型自动序列化为字符串:

@Configuration
public class JacksonConfig {

    @Bean
    @Primary
    public ObjectMapper objectMapper() {
        ObjectMapper mapper = new ObjectMapper();

        // Java 8 日期时间支持
        mapper.registerModule(new JavaTimeModule());
        mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

        // 去掉 null 字段
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

        // 将 Long / long 转为 String
        SimpleModule idModule = new SimpleModule();
        idModule.addSerializer(Long.class, ToStringSerializer.instance);
        idModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
        idModule.addSerializer(BigInteger.class, ToStringSerializer.instance);
        mapper.registerModule(idModule);

        return mapper;
    }
}

上述配置无需在 POJO 上添加注解,确保所有后端输出中的 Long/BigInteger 都以字符串形式传输。这是社区常用解决方案,也是 StackOverflow 推荐做法 (github.com, stackoverflow.com)。


3. 精准控制(可选)

如有需求,仅针对某些字段转换,新增注解支持:

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.METHOD})
@JacksonAnnotationsInside
@JsonSerialize(using = ToStringSerializer.class)
public @interface StringId {}

使用方式:

public class User {
    @StringId
    private Long id;
    private String name;
}

并在全局配置中扫描该注解,使用 BeanSerializerModifier 判断并替换:

@Bean
public Jackson2ObjectMapperBuilderCustomizer customIdSerializer() {
    return builder -> builder.modules(new SimpleModule() {
        @Override
        public void setupModule(SetupContext context) {
            context.addBeanSerializerModifier(new BeanSerializerModifier() {
                @Override
                public List<BeanPropertyWriter> changeProperties(
                        SerializationConfig config,
                        BeanDescription beanDesc,
                        List<BeanPropertyWriter> props) {
                    return props.stream().map(writer -> {
                        if (writer.getAnnotation(StringId.class) != null) {
                            return writer.withSerializer(ToStringSerializer.instance);
                        }
                        return writer;
                    }).toList();
                }
            });
        }
    });
}

4. OpenAPI (SpringDoc) 类型同步

为了 Swagger 文档中显示 ID 为 “string” 而不是 “integer”,增加 OpenAPI 自定义:

@Bean
public OpenApiCustomiser idAsStringSchemaCustomizer() {
    return openApi -> {
        openApi.getComponents().getSchemas().forEach((name, schema) -> {
            if (schema.getProperties() != null) {
                schema.getProperties().forEach((propName, propSchema) -> {
                    if (propName.toLowerCase().endsWith("id") 
                        && "integer".equals(propSchema.getType())) {
                        propSchema.setType("string");
                        propSchema.setFormat("int64");
                    }
                });
            }
        });
    };
}

📌 使用步骤总结

  1. 引入依赖 - Jackson、JSR‑310、SpringDoc。
  2. 配置全局 ObjectMapper - Long/String 自动转换。
  3. (可选)添加 @StringId 注解 - 精细控制。
  4. 同步 OpenAPI Schema 类型 - Swagger 查看准确。
  5. 测试验证:序列化、反序列化均正常。

✅ 测试示例

@SpringBootTest
public class IdConversionTest {
    @Autowired ObjectMapper mapper;

    @Test
    void testLongToString() throws Exception {
        TestEntity e = new TestEntity();
        e.setId(1234567890123456789L);
        String json = mapper.writeValueAsString(e);
        assertTrue(json.contains("\"id\":\"1234567890123456789\""));
    }

    @Test
    void testStringToLong() throws Exception {
        String json = "{\"id\":\"1234567890123456789\"}";
        TestEntity e = mapper.readValue(json, TestEntity.class);
        assertEquals(1234567890123456789L, e.getId());
    }

    static class TestEntity { Long id; /* getter-setter */ }
}

这样可以 无感 在后端处理,前端收到字符串,避免 JS 精度问题,同时 Swagger 文档也保持一致。
如果需要我帮你快速落地这套配置在你项目中,可以提供你 Spring Boot 和 SpringDoc 版本,我来进一步定制配置。


网站公告

今日签到

点亮在社区的每一天
去签到