1

I have a json string generated as follows:

System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(typeof(Data));
System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(mdata.GetType());

MemoryStream ms = new MemoryStream();
serializer.WriteObject(ms, mdata);
string json = Encoding.UTF8.GetString(ms.ToArray());

I want the null entries in the mdata structure not to be present in the json string so is there a straightforward way to do so (without having to parse the json string) ?

Thanks

xain
  • 13,159
  • 17
  • 75
  • 119

2 Answers2

1

You can set DataMember attribute option IsRequired to false:

[DataMember(IsRequired = false)]
public int Property { get; set; }

Also, some libraries can exclude default or null values without modifying DataContract classes. For example, Json.NET.

msergey
  • 592
  • 1
  • 4
  • 12
0

I think this will answer your question: Can JavaScriptSerializer exclude properties with null/default values?

Community
  • 1
  • 1
tehshin
  • 866
  • 4
  • 7