Search code examples
c#floating-pointjson.net

Deserialize float number into a 'float' type instead of default 'double' in Json.NET


Actually, the question is in the title already. Providing more details, I have to specify that I know about a custom converters and would like to avoid this scenario. I hope may be there is a setting which I can use to tune serializer for using float instead of double by default.

For example, we can use FloatParseHandling.Decimal for same purpose to use decimal instead, but not for float.

The model, which I expect to deserialize into:

public class Figure
{
    public float SideA { get; set; }
    public float SideB { get; set; }
    public float SideC { get; set; }
}

Solution

  • There is no problems when deserializing. Show your code

        #r "nuget:Newtonsoft.Json/13.0.1"
        using Newtonsoft.Json;
        using Newtonsoft.Json.Linq;
    
        var json = "{ \"num\": 1.5 }";
    
        var jAnon = JsonConvert.DeserializeAnonymousType(json , new { num = 0.0f }); // Use anonymous type
        var jClass = JsonConvert.DeserializeObject<Json>(json); // use class
        var jObj = JObject.Parse(json);
    
        var value = jObj.GetValue("num");
        value.Value<float>(); // use JObject
    
        class Json {
          public float Num {get;set;}
        }