Modify DataContractJsonSerializer Behavior

Julio Bello 221 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
.NET
Microsoft Technologies based on the .NET software framework.
3,261 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.
10,094 questions
.NET Runtime
.NET Runtime
.NET: Microsoft Technologies based on the .NET software framework.Runtime: An environment required to run apps that aren't compiled to machine language.
1,109 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Viorel 110.7K 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,571 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