如何避免 spring restful api 中 long 类型序列化为 string
在 spring 应用中,将 long 类型数据序列化为 json 字符串时,如果希望在 restful api 和内部服务之间采用不同的序列化机制,这里提供一种方法:
针对 restful api:
配置 @restcontroller 类的 produces 属性:
@restcontroller @requestmapping(value = "/api", produces = "application/json") public class myrestcontroller {
在 application.properties 中配置消息转换器:
spring.jackson.serialization.write_dates_as_timestamps=false
针对内部服务:
配置 feign 客户端的编码器:
@springbootapplication public class myapplication { public static void main(string[] args) { springapplication.run(myapplication.class, args); } @bean public encoder feignencoder() { return new springencoder(new mappingjackson2httpmessageconverter( new jackson2objectmapperbuilder().build() )); } }
java 对象的映射器:
import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import java.math.BigInteger; @RestController public class MyController { // 确保注入的不是容器里的 ObjectMapper @Autowired private ObjectMapper objectMapper; @GetMapping("/demo") public String demo() { return objectMapper.writeValueAsString(BigInteger.valueOf(1L)); } }
通过上述配置,restful api 将long 值序列化为字符串,而内部服务不会转换。
以上就是Spring RESTful API中如何避免Long类型序列化为String?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号