欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Springboot3+將ID轉(zhuǎn)為JSON字符串的詳細(xì)配置方案

 更新時(shí)間:2025年06月11日 16:12:03   作者:墮落年代  
這篇文章主要介紹了純后端實(shí)現(xiàn) Long/BigInteger ID 轉(zhuǎn)為 JSON 字符串 的詳細(xì)配置方案,s 基于 Spring Boot 3+ 和 SpringDoc (OpenAPI) 最新實(shí)踐,需要的可以了解下

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 配置

創(chuàng)建一個(gè)全局 ObjectMapper,讓所有 Long 類(lèi)型自動(dòng)序列化為字符串:

@Configuration
public class JacksonConfig {

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

        // Java 8 日期時(shí)間支持
        mapper.registerModule(new JavaTimeModule());
        mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

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

        // 將 Long / long 轉(zhuǎn)為 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;
    }
}

上述配置無(wú)需在 POJO 上添加注解,確保所有后端輸出中的 Long/BigInteger 都以字符串形式傳輸。這是社區(qū)常用解決方案,也是 StackOverflow 推薦做法 。

3. 精準(zhǔn)控制(可選)

如有需求,僅針對(duì)某些字段轉(zhuǎn)換,新增注解支持:

@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) 類(lèi)型同步

為了 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");
                    }
                });
            }
        });
    };
}

使用步驟總結(jié)

引入依賴 - Jackson、JSR?310、SpringDoc。

配置全局 ObjectMapper - Long/String 自動(dòng)轉(zhuǎn)換。

(可選)添加 @StringId 注解 - 精細(xì)控制。

同步 OpenAPI Schema 類(lèi)型 - Swagger 查看準(zhǔn)確。

測(cè)試驗(yàn)證:序列化、反序列化均正常。

測(cè)試示例

@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 */ }
}

這樣可以 無(wú)感 在后端處理,前端收到字符串,避免 JS 精度問(wèn)題,同時(shí) Swagger 文檔也保持一致。

如果需要我?guī)湍憧焖俾涞剡@套配置在你項(xiàng)目中,可以提供你 Spring Boot 和 SpringDoc 版本,我來(lái)進(jìn)一步定制配置。

到此這篇關(guān)于Springboot3+將ID轉(zhuǎn)為JSON字符串的詳細(xì)配置方案的文章就介紹到這了,更多相關(guān)Springboot ID轉(zhuǎn)JSON字符串內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論