38

我正在使用 JavaScriptSerializer 序列化一些实体对象。

问题是,许多公共属性包含空值或默认值。有没有办法让 JavaScriptSerializer 排除具有 null 或默认值的属性?

我希望生成的 JSON 不那么冗长。

4

7 回答 7

34

仅供参考,如果您想使用更简单的解决方案,以下是我使用带有 JavaScriptSerializer 的 JavaScriptConverter 实现来完成此操作的方法:

private class NullPropertiesConverter: JavaScriptConverter {
 public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) {
  throw new NotImplementedException();
 }

 public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer) {
  var jsonExample = new Dictionary<string, object >();
  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<Type> SupportedTypes {
  get {
   return GetType().Assembly.GetTypes();
  }
 }
}

然后使用它:

var serializer = new JavaScriptSerializer();
serializer.RegisterConverters(new JavaScriptConverter[] {
  new NullPropertiesConverter()
});
return serializer.Serialize(someObjectToSerialize);
于 2012-07-19T21:09:55.587 回答
14

对我有用的解决方案:

序列化的类和属性将被装饰如下:

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

IsRequired 是关键项目。

实际的序列化可以使用 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*/)
  {
    returnVal = "";
    //log error
  }
  return returnVal;
}
于 2010-02-08T21:55:24.790 回答
5

为了那些在谷歌上找到这个的人的利益,请注意,在使用 Newtonsoft.Json 进行序列化期间,可以本机跳过空值

var json = JsonConvert.SerializeObject(
            objectToSerialize,
            new JsonSerializerSettings {NullValueHandling = NullValueHandling.Ignore});
于 2017-08-31T15:10:02.683 回答
4

Json.NET具有自动排除空值或默认值的选项。

于 2009-09-07T21:55:45.403 回答
4

您可以使用 的方法实现JavaScriptConverter并注册它。RegisterConvertersJavaScriptSerializer

于 2009-09-07T06:12:57.927 回答
1

此代码是数字类型的块 null 和 default(0) 值

private class NullPropertiesConverter: JavaScriptConverter {
 public override object Deserialize(IDictionary < string, object > dictionary, Type type, JavaScriptSerializer serializer) {
  throw new NotImplementedException();
 }

 public override IDictionary < string, object > Serialize(object obj, JavaScriptSerializer serializer) {
  var jsonExample = new Dictionary < string,
   object > ();
  foreach(var prop in obj.GetType().GetProperties()) {
   //this object is nullable 
   var nullableobj = prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable < > );
   //check if decorated with ScriptIgnore attribute
   bool ignoreProp = prop.IsDefined(typeof(ScriptIgnoreAttribute), true);

   var value = prop.GetValue(obj, System.Reflection.BindingFlags.Public, null, null, null);
   int i;
   //Object is not nullable and value=0 , it is a default value for numeric types 
   if (!(nullableobj == false && value != null && (int.TryParse(value.ToString(), out i) ? i : 1) == 0) && value != null && !ignoreProp)
    jsonExample.Add(prop.Name, value);
  }

  return jsonExample;
 }

 public override IEnumerable < Type > SupportedTypes {
  get {
   return GetType().Assembly.GetTypes();
  }
 }
}
于 2016-10-06T09:43:30.810 回答
0

无需更改脚趾 DataContractSerializer

您可以使用 ScriptIgnoreAttribute

[1] http://msdn.microsoft.com/en-us/library/system.web.script.serialization.scriptignoreattribute.aspx

于 2013-03-25T14:15:58.573 回答