我们为什么推荐在Json中使用string表示Number属性值
在這篇簡短的文章中,我將解釋在使用JSON傳輸數據時,為什么浮點數或大十進制值應表示為字符串 。
long類型引發的詭異情況
長話短說,同事在利用swagger對接后端API時,詭異的發現swaggerUI中顯示的json屬性值并不是api返回的值。
[HttpGet] public IActionResult QueryAsync() {var testJson = new{Id = 123123126964992223,Profile = "Please attention on Id",};return new JsonResult(testJson); }該API在swagger輸出:
{"Id": 123123126964992220,"Profile": "Please attention on Id"}進一步從Chrome->[Network]->[Preview]、[Response payload]觀察到該long屬性值的差異。
直接給結論:部分long類型值(最大值2^63^-1)會超過Javascript的最大安全Number(2^53^-1), 瀏覽器/前端 使用JSON.parse(123123126964992223)將不再保證準確性。
將JSON中的數字值作為字符串傳輸的是為了消除傳輸中的精度丟失或歧義性。
JSON規范中未給數值指定精度,JSON解析器會自由選擇合適的數值精度。如果您的應用程序具有特定的精度要求,那么不同的JSON解析器可能不能正確表達精度。
另外部分long類型值(最大值263-1)會超過Javascript的最大安全Number(253 -1), 前端json反序列化時也會出現錯誤。
stackoverflow有個解釋很贊:
覆寫.NET Core序列化框架,將long轉化為string
針對NewtonsoftJson編寫BigIntJsonConvert
public class BigIntJsonConverter : JsonConverter<long>{public override long ReadJson(JsonReader reader, Type objectType, [AllowNull] long existingValue, bool hasExistingValue, JsonSerializer serializer){var flag = long.TryParse(reader.Value.ToString(), out long num);return flag == true ? num : 0;}public override void WriteJson(JsonWriter writer, [AllowNull] long value, JsonSerializer serializer){writer.WriteValue(value.ToString());}}// 截取自Startup.cs ConfigureServices函數context.Services.AddMvc().AddNewtonsoftJson(options => {options.SerializerSettings.Converters.Add(new BigIntJsonConverter()); });https://stackoverflow.com/questions/35709595/why-would-you-use-a-string-in-json-to-represent-a-decimal-number
關注我們
更多干貨及潮流技術
請關注Dotnet Plus公眾號
▲
▲
“閱讀全文,體驗更佳”
總結
以上是生活随笔為你收集整理的我们为什么推荐在Json中使用string表示Number属性值的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [翻译]欢迎使用C#9.0
- 下一篇: 记一次排查线上程序内存的忽高忽低,又是大