基于查询参数的条件成员序列化? [英] Conditional member serialization based on query parameter?

查看:19
本文介绍了基于查询参数的条件成员序列化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想根据查询参数与属性的匹配来控制将模型中的哪些属性序列化为我的 WebAPI2 JSON 响应.我主要想这样做是为了减少 GET 的带宽,而不会导致 ViewModel 类的激增.例如:

I would like to control which properties from my model are serialized to my WebAPI2 JSON response, based on matching a query parameter to an attribute. I mainly want to do this to reduce bandwidth on GETs without causing a proliferation of ViewModel classes. For example:

GET /books/1?format=summary

public class Book
{
    [SerializeFormat("summary")]
    public int Id { get; set; }

    [SerializeFormat("summary")]
    public string Title { get; set; }

    public string Contents { get; set; }
}

[SerializeFormat("summary","Id","Title")]
public class Book
{ ... }

为了自己做这件事,我可以从实现 ISerializable 的自定义基础派生我的所有模型类.在 ISerializable.GetObjectData() 中,遍历检查属性的所有属性.不确定这个想法的表现.

To do this myself, I could derive all of my model classes from a custom base implementing ISerializable. In ISerializable.GetObjectData(), iterate through all properties inspecting the attributes. Not sure about performance on this idea.

不想重新发明这个解决方案,尽管它已经作为一个包存在.

Don't want to reinvent this solution, though if it already exists as a package.

推荐答案

一种可能性是引入自定义 attribute JsonConditionalIncludeAttribute 可以应用于属性和字段:

One possibility would be to introduce a custom attribute JsonConditionalIncludeAttribute that can be applied to properties and fields:

[System.AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = true, Inherited = true)]
public class JsonConditionalIncludeAttribute : System.Attribute
{
    public JsonConditionalIncludeAttribute(string filterName)
    {
        this.FilterName = filterName;
    }

    public string FilterName { get; private set; }
}

接下来,子类 DefaultContractResolver,覆盖 CreateProperty,并为属性返回 null至少应用了一个 [JsonConditionalInclude],其中没有一个与提供给合约解析器的过滤器匹配:

Next, subclass DefaultContractResolver, override CreateProperty, and return null for properties that have at least one [JsonConditionalInclude] applied, none of which match the a filter supplied to the contract resolver:

public class JsonConditionalIncludeContractResolver : DefaultContractResolver
{
    public JsonConditionalIncludeContractResolver(string filterName)
    {
        this.FilterName = filterName;
    }

    public string FilterName { get; set; }

    protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
    {
        var property = base.CreateProperty(member, memberSerialization);
        // Properties without JsonConditionalIncludeAttribute applied are serialized unconditionally.
        // Properties with JsonConditionalIncludeAttribute are serialized only if one of the attributes
        // has a matching filter name.
        var attrs = property.AttributeProvider.GetAttributes(typeof(JsonConditionalIncludeAttribute), true);
        if (attrs.Count > 0 && !attrs.Cast<JsonConditionalIncludeAttribute>().Any(a => a.FilterName == FilterName))
            return null;
        return property;
    }
}

最后,在将类序列化为 JSON 时,设置 JsonSerializerSettings.ContractResolver 等同于您的自定义合同解析器,从您的网络请求中初始化 FilterName,例如:

Finally, when serializing your class to JSON, set JsonSerializerSettings.ContractResolver equal to your custom contract resolver, initializing the FilterName from your web request, for instance:

public class TestClass
{
    public string Property1 { get; set; }

    [JsonConditionalInclude("summary")]
    [JsonConditionalInclude("title")]
    public string Property2 { get; set; }

    [JsonConditionalInclude("summary")]
    public string Property3 { get; set; }

    [JsonConditionalInclude("title")]
    [JsonConditionalInclude("citation")]
    public string Property4 { get; set; }

    [JsonConditionalInclude("citation")]
    public string Field1;

    public static void Test()
    {
        var test = new TestClass { Property1 = "a", Property2 = "b", Property3 = "c", Property4 = "d", Field1 = "e" };
        Test(test, "summary"); // Prints "a", "b" and "c"
        Test(test, "title");   // Prints "a", "b" and "d".
        Test(test, "citation");// Prints "e", "a" and "d"
        Test(test, null);      // Prints "e", "a", "b", "c" and "d".
    }

    public static string Test(TestClass test, string webRequestFormat)
    {
        var settings = new JsonSerializerSettings { ContractResolver = new JsonConditionalIncludeContractResolver(webRequestFormat) };

        var json = JsonConvert.SerializeObject(test, Formatting.Indented, settings);

        Debug.WriteLine(json);
        return json;
    }
}

契约解析器将应用于所有被序列化的类,而不仅仅是根类,这看起来是你想要的.

The contract resolver will apply to all classes being serialized, not just the root class, which looks to be what you want.

这篇关于基于查询参数的条件成员序列化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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