您好,登錄后才能下訂單哦!
這篇文章主要介紹“SpringBoot如何解決BigDecimal傳到前端后精度丟失問題”,在日常操作中,相信很多人在SpringBoot如何解決BigDecimal傳到前端后精度丟失問題問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”SpringBoot如何解決BigDecimal傳到前端后精度丟失問題”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!
Controller
package com.knife.controller; import com.knife.entity.UserVO; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.math.BigDecimal; @RestController @RequestMapping("user") public class UserController { @GetMapping("save") public UserVO save(BigDecimal amount) { UserVO userVO = new UserVO(); userVO.setId(1L); userVO.setUsername("Tony"); userVO.setAmount(amount); return userVO; } }
Entity
package com.knife.entity; import lombok.Data; import java.math.BigDecimal; @Data public class UserVO { private Long id; private String username; private BigDecimal amount; }
測試
訪問:http://localhost:8080/user/save?amount=12345671234567.1234
結果
場景描述
實際項目中前端會這樣處理:調用后端接口獲得JSON格式的響應字符串,然后將JSON字符串解析為JavaScript對象(用于展示到對應的位置、方便計算等)。
前端調后端的寫接口(增刪改)時,會將JavaScript對象序列化為JSON格式的字符串,然后將其作為參數請求后端接口。
實例1:精度丟失
const json = '{"id": 1, "name": "Tony", "amount": 12345671234567.12345}'; const obj = JSON.parse(json); console.log(obj.amount); // 12345671234567.123 console.log(JSON.stringify(obj)); // {"id":1,"name":"Tony","amount":12345671234567.123}
可以看到,在將json字符串轉為JavaScript對象后,“amount” 丟失了精度。
實例2:丟失小數位
const json = '{"id": 1, "name": "Tony", "amount": 12345671234567.00000}'; const obj = JSON.parse(json); console.log(obj.amount); // 12345671234567 console.log(JSON.stringify(obj)); // {"id":1,"name":"Tony","amount":12345671234567}
可以看到,在將json字符串轉為JavaScript對象后,“amount” 丟失了小數。
其他示例
const json = '{"id": 1, "name": "Tony", "amount": 12345671234567.12345}'; const obj = JSON.parse(json); console.log(obj.amount); // 12345671234567.123 const json = '{"id": 1, "name": "Tony", "amount": 123456712345678.12345}'; const obj = JSON.parse(json); console.log(obj.amount); // 123456712345678.12 const json = '{"id": 1, "name": "Tony", "amount": 98765432198765.12345}'; const obj = JSON.parse(json); console.log(obj.amount); // 98765432198765.12 const json = '{"id": 1, "name": "Tony", "amount": 987654321987654321.12345}'; const obj = JSON.parse(json); console.log(obj.amount); // 987654321987654300
1.范圍沒有限制,可以認為無限大、無限小
2.可以通過如下代碼驗證:
package com.example.a; import java.math.BigDecimal; public class Demo { public static void main(String[] args) { BigDecimal bigDecimal = new BigDecimal( "1234567890123456789012345678901234567890" + "1234567890123456789012345678901234567890" + ".123456789" ); System.out.println(bigDecimal); } }
執行結果:
12345678901234567890123456789012345678901234567890123456789012345678901234567890.123456789
把BigDecimal的序列化值改成字符串類型即可。
法1:ToStringSerializer
配置類
package com.knife.config; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.module.SimpleModule; import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; import java.math.BigDecimal; @Configuration public class JacksonConfig { @Bean public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) { ObjectMapper objectMapper = builder.createXmlMapper(false).build(); // 全局配置序列化返回 JSON 處理 SimpleModule simpleModule = new SimpleModule(); // 將使用String來序列化BigDecimal類型 simpleModule.addSerializer(BigDecimal.class, ToStringSerializer.instance); objectMapper.registerModule(simpleModule); return objectMapper; } }
測試
訪問:http://localhost:8080/user/save?amount=12345671234567.1234
結果:
法2:自定義序列化
自定義序列化器
package com.knife.config; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.annotation.JacksonStdImpl; import com.fasterxml.jackson.databind.jsontype.TypeSerializer; import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; import java.io.IOException; import java.math.BigDecimal; import java.math.RoundingMode; @JacksonStdImpl class BigDecimalToStringSerializer extends ToStringSerializer { public final static BigDecimalToStringSerializer instance = new BigDecimalToStringSerializer(); public BigDecimalToStringSerializer() { super(Object.class); } public BigDecimalToStringSerializer(Class<?> handledType) { super(handledType); } @Override public boolean isEmpty(SerializerProvider prov, Object value) { if (value == null) { return true; } String str = ((BigDecimal) value).stripTrailingZeros().toPlainString(); return str.isEmpty(); } @Override public void serialize(Object value, JsonGenerator gen, SerializerProvider provider) throws IOException { gen.writeString(((BigDecimal) value).stripTrailingZeros().toPlainString()); // 如果要求所有BigDecimal保留兩位小數,可以這么寫: // gen.writeString(((BigDecimal) value).setScale(2, RoundingMode.HALF_UP) // .stripTrailingZeros().toPlainString()); } @Override public void serializeWithType(Object value, JsonGenerator gen, SerializerProvider provider, TypeSerializer typeSer) throws IOException { // no type info, just regular serialization serialize(value, gen, provider); } }
配置類
package com.knife.config; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.module.SimpleModule; import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; import java.math.BigDecimal; @Configuration public class JacksonConfig { @Bean public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) { ObjectMapper objectMapper = builder.createXmlMapper(false).build(); // 全局配置序列化返回 JSON 處理 SimpleModule simpleModule = new SimpleModule(); // 將使用String來序列化BigDecimal類型 simpleModule.addSerializer(BigDecimal.class, BigDecimalToStringSerializer.instance); objectMapper.registerModule(simpleModule); return objectMapper; } }
測試
訪問:http://localhost:8080/user/save?amount=12345671234567.1234
結果:
法1:@JsonSerialize
在相應字段上加此注解:
@JsonSerialize(using= ToStringSerializer.class)
示例
package com.knife.entity; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; import lombok.Data; import java.math.BigDecimal; @Data public class UserVO { private Long id; private String username; @JsonSerialize(using= ToStringSerializer.class) private BigDecimal amount; }
測試
訪問:http://localhost:8080/user/save?amount=12345671234567.1234
結果:
法2:@JsonFormat
在相應字段上加此注解:
@JsonFormat(shape = JsonFormat.Shape.STRING)
示例
package com.knife.entity; import com.fasterxml.jackson.annotation.JsonFormat; import lombok.Data; import java.math.BigDecimal; @Data public class UserVO { private Long id; private String username; @JsonFormat(shape = JsonFormat.Shape.STRING) private BigDecimal amount; }
測試
訪問:http://localhost:8080/user/save?amount=12345671234567.1234
結果:
到此,關于“SpringBoot如何解決BigDecimal傳到前端后精度丟失問題”的學習就結束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續學習更多相關知識,請繼續關注億速云網站,小編會繼續努力為大家帶來更多實用的文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。