DataContractJsonSerializer to skip nodes with null values

こ雲淡風輕ζ 提交于 2019-12-03 23:29:17

问题


I am using DataContractJsonSerializer to serialize my custom object to JSON. But i want to skip the data members whose values are null. If DataMember is null that node should not come in JSON string.

How can I achieve this? Give me a simple code snippet to work with.


回答1:


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()));
    }
}


来源:https://stackoverflow.com/questions/13506630/datacontractjsonserializer-to-skip-nodes-with-null-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!