本站资源收集于互联网,不提供软件存储服务,每天免费更新优质的软件以及学习资源!

SpringRESTfulAPI中如何避免Long类型序列化为String?

网络教程 app 1℃

SpringRESTfulAPI中如何避免Long类型序列化为String

如何避免 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 客户端的编码器:

@springbootapplicationpublic 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 .fasterxml.jackson.databind.ObjectMapper;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController;import java.math.BigInteger;@RestControllerpublic 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?的详细内容,更多请关注范的资源库其它相关文章!

转载请注明:范的资源库 » SpringRESTfulAPI中如何避免Long类型序列化为String?

喜欢 (0)