JavaScriptSerializer 可以排除具有 null/默认值的属性吗?

发布于 2024-08-04 05:22:22 字数 150 浏览 11 评论 0原文

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

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

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

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

木緿 2024-08-11 05:22:22

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

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);

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<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();
  }
 }
}

and then to use it:

var serializer = new JavaScriptSerializer();
serializer.RegisterConverters(new JavaScriptConverter[] {
  new NullPropertiesConverter()
});
return serializer.Serialize(someObjectToSerialize);
家住魔仙堡 2024-08-11 05:22:22

对我有用的解决方案:

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

[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;
}

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*/)
  {
    returnVal = "";
    //log error
  }
  return returnVal;
}
纸短情长 2024-08-11 05:22:22

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

var json = JsonConvert.SerializeObject(
            objectToSerialize,
            new JsonSerializerSettings {NullValueHandling = NullValueHandling.Ignore});

For the benefit of those who find this on google, note that nulls can be skipped natively during serialization with Newtonsoft.Json

var json = JsonConvert.SerializeObject(
            objectToSerialize,
            new JsonSerializerSettings {NullValueHandling = NullValueHandling.Ignore});
Smile简单爱 2024-08-11 05:22:22

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

独自唱情﹋歌 2024-08-11 05:22:22

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

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

最美不过初阳 2024-08-11 05:22:22

此代码是数字类型的块 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();
  }
 }
}

This code is block null and default(0) values for numeric types

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();
  }
 }
}
人事已非 2024-08-11 05:22:22

无需更改 DataContractSerializer

您可以使用 ScriptIgnoreAttribute

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

Without changing toe DataContractSerializer

You can use ScriptIgnoreAttribute

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文