Springboot3+將ID轉(zhuǎn)為JSON字符串的詳細(xì)配置方案
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)文章
Spring實(shí)現(xiàn)定時(shí)任務(wù)的兩種方法詳解
Spring提供了兩種方式實(shí)現(xiàn)定時(shí)任務(wù),一種是注解,還有一種就是接口了,這篇文章主要為大家介紹了這兩種方法的具體實(shí)現(xiàn)方法,需要的可以參考下2024-12-12java使用JDBC動(dòng)態(tài)創(chuàng)建數(shù)據(jù)表及SQL預(yù)處理的方法
這篇文章主要介紹了java使用JDBC動(dòng)態(tài)創(chuàng)建數(shù)據(jù)表及SQL預(yù)處理的方法,涉及JDBC操作數(shù)據(jù)庫(kù)的連接、創(chuàng)建表、添加數(shù)據(jù)、查詢等相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下2017-08-08Struts2實(shí)現(xiàn)對(duì)action請(qǐng)求對(duì)象的攔截操作方法
這篇文章主要介紹了Struts2實(shí)現(xiàn)對(duì)action請(qǐng)求對(duì)象的攔截操作方法,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2017-11-11Spring?Boot?啟動(dòng)參數(shù)之如何優(yōu)雅地控制你的應(yīng)用(最新推薦)
Spring Boot 提供了哪些方式來(lái)配置這些啟動(dòng)參數(shù),今天我們就來(lái)詳細(xì)解析 Spring Boot 啟動(dòng)參數(shù)的各種用法,并附帶代碼示例,讓你可以靈活掌控應(yīng)用的啟動(dòng)過(guò)程,需要的朋友可以參考下2025-04-04詳解Elasticsearch如何實(shí)現(xiàn)簡(jiǎn)單的腳本排序
Elasticsearch?是位于?Elastic?Stack?核心的分布式搜索和分析引擎,可以為所有類(lèi)型的數(shù)據(jù)提供近乎實(shí)時(shí)的搜索和分析。本文主要介紹了Elasticsearch如何實(shí)現(xiàn)簡(jiǎn)單的腳本排序,感興趣的可以了解一下2023-01-01springcloud?feign服務(wù)之間調(diào)用,date類(lèi)型轉(zhuǎn)換錯(cuò)誤的問(wèn)題
這篇文章主要介紹了springcloud?feign服務(wù)之間調(diào)用,date類(lèi)型轉(zhuǎn)換錯(cuò)誤的問(wèn)題及解決,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-03-03深入理解Java責(zé)任鏈模式實(shí)現(xiàn)靈活的請(qǐng)求處理流程
本文詳細(xì)介紹了Java中的責(zé)任鏈模式,幫助您理解其工作原理,以及如何在代碼中實(shí)現(xiàn)。該模式可以將請(qǐng)求沿著處理鏈路傳遞,實(shí)現(xiàn)靈活的請(qǐng)求處理流程。通過(guò)本文的學(xué)習(xí),您將獲得在Java應(yīng)用程序中使用責(zé)任鏈模式的知識(shí)和技能2023-04-04Spring中容器的創(chuàng)建流程詳細(xì)解讀
這篇文章主要介紹了Spring中容器的創(chuàng)建流程詳細(xì)解讀,Spring?框架其本質(zhì)是作為一個(gè)容器,提供給應(yīng)用程序需要的對(duì)象,了解容器的誕生過(guò)程,有助于我們理解?Spring?框架,也便于我們“插手”這個(gè)過(guò)程,需要的朋友可以參考下2023-10-10