类中的 ShouldSerialize () 重构...我可以使用 IContractResolver 吗? [英] Refactor of ShouldSerialize () in class... can I use IContractResolver?

查看:24
本文介绍了类中的 ShouldSerialize () 重构...我可以使用 IContractResolver 吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 API 可以返回一个很大的汽车功能列表....都是 bool 或 ints...基本上我只想显示那些返回真值或 >0 的整数.

I have an API that returns a big list of car features.... all are either bool or ints... and basically I only want to display the ones that return true values or >0 for the ints.

我正在使用 JSON.net,因此我可以使用 ShouldSerialize() 属性来确定是否应该根据属性值对其进行序列化,我的代码如下所示:

I am using JSON.net so that I san use the ShouldSerialize() property to determine if I should serialize the property based upon its value and my code looks like this:

public class Features
{
    public bool ABS { get; set; }

    public bool ShouldSerializeABS()
    {
        // don't serialize the ABS property if ABS is false
        return (ABS != false);
    }


    public bool Immobiliser { get; set; }

    public bool ShouldSerializeImmobiliser ()
    {
        // don't serialize the Immobiliser property if Immobiliser is false
        return (Immobiliser != false);
    }

    public int BHP { get; set; }

    public bool ShouldSerializeBHP  ()
    {
        // don't serialize the BHP property if BHP is false
        return (BHP != 0);
    }
    //..... etc
}

这很好用,并为我提供了我想要的结果,但是我只是想知道是否有办法重新考虑这个问题,这样我的类就不会被所有的 ShouldSerialize() 属性弄得乱七八糟?

This works great and gives me the results I am after, however I was just wondering if there is a way to re-factor this so that my class does not become cluttered with all the ShouldSerialize() properties?

我一直在使用 IContractResolverhttp://james.newtonking.com/projects/json/help/index.html?topic=html/ConditionalProperties.htm 看起来像可能可以将 IContractResolver 用于这样的目的,但我似乎最终还是得到了很多似乎没有重新分解的代码

I have been looking into CopyConditional properties with IContractResolver on http://james.newtonking.com/projects/json/help/index.html?topic=html/ConditionalProperties.htm and looks like it might be possible to use IContractResolver for such a purpose, but I still seem to end up with lots of code that does not seem to re-factor out

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(Features) && property.PropertyName == "ABS")
     {
         property.ShouldSerialize =
           instance =>
           {
               Features e = (Features)instance;
               return e.ABS != false;
           };
     }
     if (property.DeclaringType == typeof(Features) && property.PropertyName == "Immobiliser")
     {
         property.ShouldSerialize =
           instance =>
           {
               Features e = (Features)instance;
               return e.Immobiliser != false;
           };
     }

    return property;
  }
}

如果该属性为 false,则使用 ShouldSerializeContractResolver 的此方法似乎不会从类中删除该属性......非常感谢任何帮助

and this method using the ShouldSerializeContractResolver does not seem to remove the property from the class if it is false... any help is greatly appreciated

推荐答案

听起来您通过编写所有这些 ShouldSerialize() 方法可以通过更改 DefaultValueHandling 设置来实现在序列化器上忽略.这将导致任何等于其默认值(bool 为 false,int 为 0)的值不会被序列化.

It sounds like what you are trying to accomplish by writing all these ShouldSerialize() methods can be accomplished by just changing the DefaultValueHandling setting on the serializer to Ignore. This will cause any values that are equal to their default values (false for bool, 0 for int) not to be serialized.

JsonSerializerSettings jsonSettings = new JsonSerializerSettings();
jsonSettings.DefaultValueHandling = DefaultValueHandling.Ignore;

string json = JsonConvert.SerializeObject(yourObject, jsonSettings);

如果您使用的是 Web API,那么您可以通过 WebApiConfig 类(在 App_Start 文件夹中)的 Register 方法访问 Json.NET 序列化程序的设置).

If you're using Web API, then you can access the settings of the Json.NET serializer via the Register method of the WebApiConfig class (in the App_Start folder).

JsonSerializerSettings settings = config.Formatters.JsonFormatter.SerializerSettings;
settings.DefaultValueHandling = DefaultValueHandling.Ignore;

这篇关于类中的 ShouldSerialize () 重构...我可以使用 IContractResolver 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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