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

3

11

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,
    // ...
}
Caisson answered 29/12, 2015 at 18:15 Comment(10)
Can we take a look at some of the json you are attempting to deserialize?Rube
Of course , thank you. I add that right nowCaisson
Using just that partial NewMap contract, your JSON input, and that very last line of your code, everything works just fine for me. No issues here. The float is correctly recognized without an error.Mcminn
Yes it's very strange.. Seems like no solution for my problem :'( , what do you mean by "just using partial NewMap contract" ?Caisson
Are you able to change the datatype from double to something else. I'm curious if a decimal would work.Hughie
Do your regional settings use something else than a dot ? msdn.microsoft.com/en-us/library/994c0zb1(v=vs.110).aspxPennypennyaliner
@LuckyPierre , i just try now to use "decimal" insteand of double. But still same. JSON try to cast as an integer when i want deserializeCaisson
@Aybe . Mhh good question. I know when i need parse Double value i use the option "CultureInfo.InvariantCulture" . But normally for JSON is the defaut value for Parse DoubleCaisson
Thank's to all of you !! I find it. Because i tried to use a specific CultureInfo as @Aybe said . Do you can please add that as an answer ?Caisson
@MehdiBugnard: In your question you mention your "Web API project", and then you call it "Web ASP project". Could you update that part of the question to be consistent, more clear or remove it altogether since it's irrelevant to the actual issue?Revenuer
P
12

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.

Pennypennyaliner answered 30/12, 2015 at 12:2 Comment(3)
I'm trying to do this now but not getting any success, can you show an example please?Caniff
InvariantCulture is the default. newtonsoft.com/json/help/html/…Cocainize
Try setting the culture of JsonConvert to CultureInfo.InvariantCulture. >>> This is still not workJoelynn
B
1

I used:

Replace(".0,","") 

And it worked for me

Brody answered 22/9, 2021 at 15:50 Comment(1)
This is a one off solution that needs to be implemented at every deserialization point, and fails to account for any number of similar errors that can occur when deserializing data using different localization settings. Given that, the approach proposed by the accepted answer is not only easier, but will address other issues not yet discovered.Contrite
T
0

If you came here because you ran into this error message, the answer may be:

'46.605' is not an integer! It has a decimal point. You need to either provide an integer, or change the object to another type.

I'm sorry, it's not an answer to the original question, but it's why I came here, and I searched how to set the culture, and whether I could change the dot to a comma while the simple answer is the data has always been a decimal, it just never had a decimal part until now, so the code expects an integer.

Tomkin answered 26/5 at 20:23 Comment(1)
This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From ReviewYoungster

© 2022 - 2024 — McMap. All rights reserved.