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

pianoboy11 1 Reputation point
2022-02-28T03:06:31.57+00:00

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

For example, I am having following JSON:

{ "Amount": NaN }

Developer technologies C#
{count} votes

2 answers

Sort by: Most helpful
  1. Jack J Jun 25,296 Reputation points
    2022-02-28T09:01:32.127+00:00

    @pianoboy11 , you could use JsonSerializerSettings to give the default value.

    Like the following code:

      static void Main(string[] args)  
            {  
                var options = new JsonSerializerOptions  
                {  
                    NumberHandling = JsonNumberHandling.AllowReadingFromString | JsonNumberHandling.AllowNamedFloatingPointLiterals  
                };  
                Test test = new Test();  
                test.Name = "test1";  
                test.Amount = double.NaN;  
                Console.WriteLine(JsonSerializer.Serialize(test,options));  
            }  
          
         public class Test  
            {  
                public string Name { get; set; }  
          
                public double Amount { get; set; }     
          
            }  
    

    Result:

    208063-image.png


    If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

  2. kenny Rodriguez Fernadez 1 Reputation point
    2022-06-03T00:10:24.273+00:00

    The solution provided it's for JSON.net, not for System.Text.Json.Serialization which uses "JsonSerializerOptions"

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.