Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# DeSerialize NaN values into JSON in using System.Text.Json.Serialization;

I need to convert NaN in Json(as it is not JSON) to Double using System.Text.Json

For example, I am having following JSON:

{ "Amount": NaN }
like image 707
user1298394 Avatar asked Jul 24 '26 02:07

user1298394


1 Answers

To serialized/deserialized, You can use an alternative way (such as strings) Json.NET stores these as strings in the payload then automatically converts to float. To demonstrate you can check the following code:

public class ClassWithNumbers
{
    public int IntNumber { get; set; }
    public float FloatNumber { get; set; }
}

// Json Serialization Options to allow literals 
var options = new JsonSerializerOptions
{
    NumberHandling = JsonNumberHandling.AllowNamedFloatingPointLiterals
};

// Json Exmple
string json = @"{""IntNumber"":1,""FloatNumber"":""NaN""}";
ClassWithNumbers obj =     System.Text.Json.JsonSerializer.Deserialize<ClassWithNumbers>(json, options);

Output:
// obj.IntNumber: 1
// obj.FloatNumber: NaN
like image 149
Muhammad Imran Ansari Avatar answered Jul 28 '26 15:07

Muhammad Imran Ansari



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!