views:

494

answers:

3

I'm using JavaScriptSerializer to serialize some entity objects.

The problem is, many of the public properties contain null or default values. Is there any way to make JavaScriptSerializer exclude properties with null or default values?

I would like the resulting JSON to be less verbose.

A: 

You can implement a JavaScriptConverter and register it using the RegisterConverters method of JavaScriptSerializer.

Vinay Sajip
+1  A: 

Json.NET has options to automatically exclude null or default values.

James Newton-King
A: 

The solution that worked for me:

The serialized class and properties would be decorated as follows:

[DataContract]
public class MyDataClass
{
  [DataMember(Name = "LabelInJson", IsRequired = false)]
  public string MyProperty { get; set; }
}

IsRequired was the key item.

The actual serialization could be done using DataContractJsonSerializer:

public static string Serialize<T>(T obj)
{
  string returnVal = "";
  try
  {
    DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
    using (MemoryStream ms = new MemoryStream())
    {
      serializer.WriteObject(ms, obj);
      returnVal = Encoding.Default.GetString(ms.ToArray());
    }
  }
  catch (Exception exception)
  {
    retVal = "";
    //log error
  }
  return returnVal;
}
frankadelic