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 }
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With