'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 }
Solution 1:[1]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Peter Csala |
