locked
System.Text.Json Deserialize empty strings to null RRS feed

  • Question

  • User-401080925 posted

    Hi

    using Blazor 3.2,is there any option not to convert empty strings to null on System.Text.Json Deserialize?

    Saturday, October 24, 2020 11:37 AM

Answers

  • User475983607 posted

    Hi

    using Blazor 3.2,is there any option not to convert empty strings to null on System.Text.Json Deserialize?

    Empty string are not converted to null.  Null is converted to null.

        public class JsonModel
        {
            public int Id { get; set; }
            public string Name { get; set; }
        }
            static async Task Main (string[] args)
            {
                JsonModel model = new JsonModel() { Id = 1, Name = "" };
                string json = JsonSerializer.Serialize(model);
                Console.WriteLine(json);
    
                model.Name = null;
                json = JsonSerializer.Serialize(model);
                Console.WriteLine(json);
            }

    Results

    {"Id":1,"Name":""}
    {"Id":1,"Name":null}

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, October 24, 2020 12:32 PM

All replies

  • User475983607 posted

    Hi

    using Blazor 3.2,is there any option not to convert empty strings to null on System.Text.Json Deserialize?

    Empty string are not converted to null.  Null is converted to null.

        public class JsonModel
        {
            public int Id { get; set; }
            public string Name { get; set; }
        }
            static async Task Main (string[] args)
            {
                JsonModel model = new JsonModel() { Id = 1, Name = "" };
                string json = JsonSerializer.Serialize(model);
                Console.WriteLine(json);
    
                model.Name = null;
                json = JsonSerializer.Serialize(model);
                Console.WriteLine(json);
            }

    Results

    {"Id":1,"Name":""}
    {"Id":1,"Name":null}

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, October 24, 2020 12:32 PM
  • User-401080925 posted

    indeed,only in debugger it is shown as null,but in Console.WriteLine it is ok

    thanks

    Saturday, October 24, 2020 1:28 PM
  • User475983607 posted

    indeed,only in debugger it is shown as null,but in Console.WriteLine it is ok

    Null and empty string are not the same types.  The serializer does NOT convert an empty string to null.  You must be missing something.  Share code that reproduces this issue so we can figure out what's going on.

    Saturday, October 24, 2020 1:37 PM
  • User-401080925 posted

    It's ok,only Blazor client-side debugging with Chrome shows null

    post can be deleted

    thanks

    Saturday, October 24, 2020 1:59 PM