JsonConvert throws a 'not a valid integer' exception when deserializing to a double

亡梦爱人 提交于 2019-12-09 05:49:30

问题


I get an exception when I try to deserialize to an object from a JSON string.

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

It's really weird because JsonConvert tries to deserialize an attribute as an integer but it actually is a double and not an integer.

I already checked in my Web API project. The attribute in my class is a double and same in web project.

The code I use in my web asp project:

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 });
}

Here is my class:

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

My JSON content:

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

回答1:


It could very well be because your regional settings use something other than a 'dot' to represent what's after the integer part of a double, such as the fr-FR culture.

A rough guess is that the JsonConvert class uses methods for parsing numbers from .NET (there's no reason why it wouldn't after all), such as Double.TryParse. And these very method do by default, take into account your current culture.

Try setting the culture of JsonConvert to CultureInfo.InvariantCulture.



来源:https://stackoverflow.com/questions/34516642/jsonconvert-throws-a-not-a-valid-integer-exception-when-deserializing-to-a-dou

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!