mirror of
https://github.com/201206030/novel-plus.git
synced 2025-04-26 09:20:50 +00:00
fix: Spring AI 流式 API 请求 400 错误
在对 RestController 返回对象 json 格式化时,将所有 Long 类型转为 String 类型返回,避免前端数据精度丢失的问题。 主要是为了取代 spring.jackson.generator.write-numbers-as-strings=true 配置,避免影响全局的 ObjectMapper
This commit is contained in:
parent
8c1c0f10be
commit
eff4fc4c7c
@ -0,0 +1,45 @@
|
||||
package com.java2nb.novel.core.advice;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.module.SimpleModule;
|
||||
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
|
||||
import org.springframework.core.MethodParameter;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.converter.HttpMessageConverter;
|
||||
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
|
||||
import org.springframework.http.server.ServerHttpRequest;
|
||||
import org.springframework.http.server.ServerHttpResponse;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
|
||||
|
||||
/**
|
||||
* 在对 RestController 返回对象 json 格式化时,将所有 Long 类型转为 String 类型返回,避免前端数据精度丢失的问题
|
||||
* 取代 spring.jackson.generator.write-numbers-as-strings=true 配置,避免影响全局的 ObjectMapper 配置
|
||||
* */
|
||||
@RestControllerAdvice
|
||||
public class CustomResponseBodyAdvice implements ResponseBodyAdvice<Object> {
|
||||
|
||||
private final ObjectMapper customObjectMapper;
|
||||
|
||||
public CustomResponseBodyAdvice(Jackson2ObjectMapperBuilder builder) {
|
||||
customObjectMapper = builder.createXmlMapper(false).build();
|
||||
SimpleModule simpleModule = new SimpleModule();
|
||||
simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
|
||||
simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
|
||||
customObjectMapper.registerModule(simpleModule);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
|
||||
// 返回 true 表示对所有 Controller 的响应都生效
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
|
||||
// 使用自定义的 ObjectMapper 序列化响应体
|
||||
return customObjectMapper.valueToTree(body);
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -6,11 +6,6 @@ spring:
|
||||
mode: LEGACYHTML5 #去除thymeleaf的html严格校验thymeleaf.mode=LEGACYHTML5
|
||||
cache: false # 是否开启模板缓存,默认true,建议在开发时关闭缓存,不然没法看到实时
|
||||
|
||||
# 将所有数字转为 String 类型返回,避免前端数据精度丢失的问题
|
||||
jackson:
|
||||
generator:
|
||||
write-numbers-as-strings: true
|
||||
|
||||
#上传文件的最大值(100M)
|
||||
servlet:
|
||||
multipart:
|
||||
|
Loading…
x
Reference in New Issue
Block a user