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}

Developer technologies | .NET | .NET Runtime
Developer technologies | .NET | Other
Developer technologies | C#
0 comments No comments
{count} votes

2 answers

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

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.