xain
xain

Reputation: 13839

Removing entries from json string in C#

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

Upvotes: 1

Views: 1899

Answers (2)

tehshin
tehshin

Reputation: 866

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

Upvotes: 0

msergey
msergey

Reputation: 612

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.

Upvotes: 1

Related Questions