通过自定义属性(json.net)从序列化中排除属性 [英] Exclude property from serialization via custom attribute (json.net)

查看:85
本文介绍了通过自定义属性(json.net)从序列化中排除属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要能够控制如何/是否对类的某些属性进行序列化.最简单的情况是[ScriptIgnore].但是,我只希望针对我正在处理的这一特定序列化情况使用这些属性-如果应用程序中下游的其他模块也希望序列化这些对象,则这些属性都不会妨碍您.

所以我的想法是在属性上使用自定义属性MyAttribute,并使用知道要查找该属性的钩子初始化JsonSerializer的特定实例.

乍一看,我看不到JSON.NET中的任何可用挂钩点都会为当前属性提供PropertyInfo来进行此类检查-仅提供属性值.我想念什么吗?还是解决这个问题的更好方法?

解决方案

您有一些选择.我建议您阅读Json.Net文档上的文章主题,然后再阅读下面的内容.

本文介绍了两种方法:

  1. 创建一个方法,该方法根据Json.Net用来确定是否序列化该属性的命名约定返回bool值.
  2. 创建一个忽略该属性的自定义合同解析器.

在这两者中,我赞成后者.完全跳过属性-仅使用它们来忽略所有形式的序列化中的属性.相反,创建一个忽略有问题的属性的自定义合同解析器,并且仅在您要忽略该属性时才使用合同解析器,从而使该类的其他用户可以随意序列化该属性,也可以不随意执行.

编辑,为避免链接腐烂,我在文章中发布了有问题的代码

public class ShouldSerializeContractResolver : DefaultContractResolver
{
   public new static readonly ShouldSerializeContractResolver Instance =
                                 new ShouldSerializeContractResolver();

   protected override JsonProperty CreateProperty( MemberInfo member,
                                    MemberSerialization memberSerialization )
   {
      JsonProperty property = base.CreateProperty( member, memberSerialization );

      if( property.DeclaringType == typeof(Employee) &&
            property.PropertyName == "Manager" )
      {
         property.ShouldSerialize = instance =>
         {
            // replace this logic with your own, probably just  
            // return false;
            Employee e = (Employee)instance;
            return e.Manager != e;
         };
      }

      return property;
   }
}

I need to be able to control how/whether certain properties on a class are serialized. The simplest case is [ScriptIgnore]. However, I only want these attributes to be honored for this one specific serialization situation I am working on - if other modules downstream in the application also want to serialize these objects, none of these attributes should get in the way.

So my thought is to use a custom attribute MyAttribute on the properties, and initialize the specific instance of JsonSerializer with a hook that knows to look for that attribute.

At first glance, I don't see any of the available hook points in JSON.NET will provide the PropertyInfo for the current property to do such an inspection - only the property's value. Am I missing something? Or a better way to approach this?

解决方案

You have a few options. I recommend you read the Json.Net documentation article on the subject before reading below.

The article presents two methods:

  1. Create a method that returns a bool value based on a naming convention that Json.Net will follow to determine whether or not to serialize the property.
  2. Create a custom contract resolver that ignores the property.

Of the two, I favor the latter. Skip attributes altogether -- only use them to ignore properties across all forms of serialization. Instead, create a custom contract resolver that ignores the property in question, and only use the contract resolver when you want to ignore the property, leaving other users of the class free to serialize the property or not at their own whim.

Edit To avoid link rot, I'm posting the code in question from the article

public class ShouldSerializeContractResolver : DefaultContractResolver
{
   public new static readonly ShouldSerializeContractResolver Instance =
                                 new ShouldSerializeContractResolver();

   protected override JsonProperty CreateProperty( MemberInfo member,
                                    MemberSerialization memberSerialization )
   {
      JsonProperty property = base.CreateProperty( member, memberSerialization );

      if( property.DeclaringType == typeof(Employee) &&
            property.PropertyName == "Manager" )
      {
         property.ShouldSerialize = instance =>
         {
            // replace this logic with your own, probably just  
            // return false;
            Employee e = (Employee)instance;
            return e.Manager != e;
         };
      }

      return property;
   }
}

这篇关于通过自定义属性(json.net)从序列化中排除属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆