JsonConvert 反序列化为 double 时抛出“不是有效整数”异常

问题描述 投票:0回答:3

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

Input string '46.605' is not a valid integer. Path 'LatitudeCenter'

这真的很奇怪,因为

JsonConvert
尝试将属性反序列化为整数,但它实际上是双精度数而不是整数

我已经签入了我的 Web API 项目。我的类中的属性是双精度的,并且在 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 });
}

这是我的课:

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,
    // ...
}
c# json asp.net-web-api double deserialization
3个回答
12
投票

这很可能是因为您的区域设置使用 'dot' 以外的其他内容来表示

double
整数部分之后的内容,例如
fr-FR
区域性。

粗略猜测,

JsonConvert
类使用从.NET解析数字的方法(毕竟没有理由不这样做),例如Double.TryParse。这些very方法默认执行,考虑到您的当前文化

尝试将

JsonConvert
的文化设置为
CultureInfo.InvariantCulture


1
投票

我用过:

Replace(".0,","") 

这对我有用


0
投票

如果您是因为遇到此错误消息而来到这里,答案可能是:

'46.605' 不是整数! 它有一个小数点。您需要提供一个整数,或者将对象更改为其他类型。

很抱歉,这不是原始问题的答案,但这就是我来这里的原因,我搜索了如何设置文化,以及是否可以将点更改为逗号,而简单的答案是数据始终是小数,直到现在它才没有小数部分,所以代码需要一个整数。

© www.soinside.com 2019 - 2024. All rights reserved.