DataContractJsonSerializer to skip nodes with null values

后端 未结 1 508
闹比i
闹比i 2021-01-07 18:35

I am using DataContractJsonSerializer to serialize my custom object to JSON. But i want to skip the data members whose values are null. If Da

相关标签:
1条回答
  • 2021-01-07 19:26

    You can use the EmitDefaultValue = false property in the [DataMember] attribute. For members marked with that attribute, their values will not be output.

    [DataContract]
    public class MyType
    {
        [DataMember(EmitDefaultValue = false)]
        public string Prop1 { get; set; }
        [DataMember(EmitDefaultValue = false)]
        public string Prop2 { get; set; }
        [DataMember(EmitDefaultValue = false)]
        public string Prop3 { get; set; }
    }
    public class Test
    {
        public static void Main()
        {
            var dcjs = new DataContractJsonSerializer(typeof(MyType));
            var ms = new MemoryStream();
            var data = new MyType { Prop2 = "Hello" };
            dcjs.WriteObject(ms, data);
    
            // This will write {"Prop2":"Hello"}
            Console.WriteLine(Encoding.UTF8.GetString(ms.ToArray()));
        }
    }
    
    0 讨论(0)
提交回复
热议问题