Can JavaScriptSerializer exclude properties with null/default values?

前端 未结 7 1140
野趣味
野趣味 2020-12-01 05:08

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 m

7条回答
  •  旧巷少年郎
    2020-12-01 05:47

    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 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*/)
      {
        returnVal = "";
        //log error
      }
      return returnVal;
    }
    

提交回复
热议问题