Modify DataContractJsonSerializer Behavior

Julio Bello 181 Reputation points
2021-03-02T19:06:15.733+00:00

Is there a way to tell the DataContractJsonSerializer not to display members/properties whose value is null?

For example: {"x": 1, "y": null, "z": 3} => {"x": 1, "z": 3}

.NET Standard
.NET Standard
A formal specification of .NET APIs that are available on multiple .NET implementations.
506 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
8,248 questions
.NET Runtime
.NET Runtime
.NET: Microsoft Technologies based on the .NET software framework.Runtime: The period of time during which a program is being executed in a computer.
1,002 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Viorel 95,261 Reputation points
    2021-03-02T20:16:39.977+00:00

    It seems to work in this case:

    [DataContract]
    class Example
    {
        [DataMember( EmitDefaultValue = false )]
        public int? x { get; set; }
    
        [DataMember( EmitDefaultValue = false )]
        public int? y { get; set; }
    
        [DataMember( EmitDefaultValue = false )]
        public int? z { get; set; }
    }
    

    If this does not work, then show your details.


  2. Timon Yang-MSFT 9,531 Reputation points
    2021-03-03T06:04:35.437+00:00

    Is it possible to use other packages,?Such as System.Text.Json, which provides specific methods to ignore empty values.

        class Program  
        {  
            static void Main(string[] args)  
            {  
                MyClass myClass = new MyClass() { ID = 1, Age = 25 };  
      
                var jsonSerializerOptions = new JsonSerializerOptions()  
                {  
                    IgnoreNullValues = true  
                };  
                string jsonString =  JsonSerializer.Serialize(myClass, jsonSerializerOptions);  
                Console.WriteLine();  
            }  
        }  
        class MyClass  
        {  
            public int ID { get; set; }  
            public string Name { get; set; }  
            public int Age { get; set; }  
        }  
    

    If the response is helpful, please click "Accept Answer" and upvote it.
    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