c# - 反序列化为 double 时 JsonConvert 抛出 'not a valid integer' 异常

标签 c# json asp.net-web-api double deserialization

当我尝试从 JSON 字符串反序列化为对象时出现异常。

输入字符串“46.605”不是有效整数。路径“纬度中心”

这真的很奇怪,因为 JsonConvert 试图将一个属性反序列化为一个整数,但它实际上是一个 double 而不是一个整数。。 p>

我已经 checkin 了我的 Web API 项目。我的类中的属性是 double 的,并且在 Web 项目中相同。

我在我的 web asp 项目中使用的代码:

using (var client = new HttpClient())
{
    client.BaseAddress = new Uri("myWebApiHostedUrl");
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    // Get the response
    HttpResponseMessage response = await client.GetAsync("api/NewMap/?SouthLatitude=46.600&WestLongitude=7.085&NorthLatitude=46.610&EastLongitude=7.095&Width=900&Height=900&isVoxelMap=true");
    string jsonData = response.Content.ReadAsStringAsync().Result;

    //Exception here
    NewMap dataMewMap = JsonConvert.DeserializeObject<NewMap>(jsonData, new JsonSerializerSettings() { Culture = CultureInfo.InvariantCulture,FloatParseHandling= FloatParseHandling.Double });
}

这是我的类(class):

public class NewMap
{
    // ...
    public double LatitudeCenter { get; set; }
    public double LongitudeCenter { get; set; }
    // ...
}

我的 JSON 内容:

{
    // ...
    "LatitudeCenter":46.605,
    "LongitudeCenter":7.09,
    "SouthLatitude":46.6,
    "ImageBingUrl":null,
    "PercentEnvironement_Plain":0,
    // ...
}

最佳答案

这很可能是因为您的区域设置使用了不同于“点”的东西来表示 double 的整数部分之后的内容,例如 fr-FR 文化。

一个粗略的猜测是 JsonConvert 类使用方法来解析来自 .NET 的数字(毕竟没有理由不这样做),例如 Double.TryParse .默认情况下,这些非常方法会考虑到您当前的文化

尝试将 JsonConvert 的文化设置为 CultureInfo.InvariantCulture

关于c# - 反序列化为 double 时 JsonConvert 抛出 'not a valid integer' 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34516642/

相关文章:

c# - WebApi—— Controller 继承——方法的新版本

c# - 使用 C# 在 Excel 中查找绘制的箭头

c# - 错误 : ExecuteReader requires an open and available Connection. 连接的当前状态为打开

c# - 通过 Cloudflare 和 Azure 获取用户的 IP 地址

json - Spring Boot Rest - OffsetDateTime 以浮点形式返回

c# - 从 C# 控制台应用程序迁移和运行 REST API 到 ASP.NET

c# - Xamarin - PopAsync() 后刷新列表

python - 加载到 BigQuery - 一列处理任意 json 字段(空数组、具有不同字段的字典等)

arrays - 我如何在 map 上快速绘制标记

c# - 名为 'MS_attributerouteWebApi' 的路由已经在路由集合中