简体   繁体   English

如何从 .NET Core 3.1 中的 JSON object 反序列化浮点数据类型

[英]How to Deserialize float datatype from JSON object in .NET Core 3.1

I am trying to pass the below JSON object to an.NET Core 3.1 API endpoint that accepts an object of type Order.我正在尝试将下面的 JSON object 传递给 an.NET Core 3.1 API 端点,该端点接受 6 类型的 ZA8CFDEFDE6331BD4BEB62669

{ 
"OrderType" : "Sale",
    "Total" : "100"
}

public class Order (){
public string OrderType {get; set;}
public float Total {get;set;}
}

This is giving me the below error.这给了我以下错误。 How can I fix this.我怎样才能解决这个问题。

Error: "The JSON value could not be converted to System.Single. Path: $.Total | LineNumber: 2 | BytePositionInLine: 21."错误:“JSON 值无法转换为 System.Single。路径:$.Total | LineNumber:2 | BytePositionInLine:21。”

ASP.Net core 3.1 does not use Newtonsoft.JSON for serialization, it uses its own serializer System.Text.Json. ASP.Net core 3.1 没有使用 Newtonsoft.JSON 进行序列化,它使用自己的序列化器 System.Text.Json。

If you want to use Newtonsoft.JSON in ASP.NET core 3.1,如果要在 ASP.NET core 3.1 中使用 Newtonsoft.JSON,

  • download Microsoft.AspNetCore.Mvc.NewtonsoftJson from NuGet package.从 NuGet package 下载 Microsoft.AspNetCore.Mvc.NewtonsoftJson。
  • In Startup.cs replace services.AddControllers();在 Startup.cs 中替换services.AddControllers(); with services.AddControllers().AddNewtonsoftJson();使用services.AddControllers().AddNewtonsoftJson();

You can refer to the below blog for more details on System.Text.Json有关 System.Text.Json 的更多详细信息,您可以参考以下博客

https://devblogs.microsoft.com/dotnet/try-the-new-system-text-json-apis/ https://devblogs.microsoft.com/dotnet/try-the-new-system-text-json-apis/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM