
如何避免 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 值序列化为字符串,而内部服务不会转换。










