Can JavaScriptSerializer exclude properties with null/default values?

前端 未结 7 1160
野趣味
野趣味 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:54

    FYI, if you'd like to go with the easier solution, here's what I used to accomplish this using a JavaScriptConverter implementation with the JavaScriptSerializer:

    private class NullPropertiesConverter: JavaScriptConverter {
     public override object Deserialize(IDictionary dictionary, Type type, JavaScriptSerializer serializer) {
      throw new NotImplementedException();
     }
    
     public override IDictionary Serialize(object obj, JavaScriptSerializer serializer) {
      var jsonExample = new Dictionary();
      foreach(var prop in obj.GetType().GetProperties()) {
       //check if decorated with ScriptIgnore attribute
       bool ignoreProp = prop.IsDefined(typeof(ScriptIgnoreAttribute), true);
    
       var value = prop.GetValue(obj, BindingFlags.Public, null, null, null);
       if (value != null && !ignoreProp)
        jsonExample.Add(prop.Name, value);
      }
    
      return jsonExample;
     }
    
     public override IEnumerable SupportedTypes {
      get {
       return GetType().Assembly.GetTypes();
      }
     }
    }
    

    and then to use it:

    var serializer = new JavaScriptSerializer();
    serializer.RegisterConverters(new JavaScriptConverter[] {
      new NullPropertiesConverter();
    });
    return serializer.Serialize(someObjectToSerialize);
    

提交回复
热议问题