通过属性将Contract Resolver应用于特定模型 [英] Applying a Contract Resolver to a specific model via an attribute

查看:47
本文介绍了通过属性将Contract Resolver应用于特定模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用内部使用Json.Net的Web API.当前,我有一种情况,我只需要将自定义合同解析器应用于一个特定模型.我可以使用[JsonConverter(typeof(MyConverter))]之类的属性应用自定义JsonConverter.是否可以以相同方式在一个模型上应用自定义合同解析器?

I am using Web API which internally uses Json.Net. Currently, I have a scenario where I need to apply a custom contract resolver only to one specific model. I can apply a custom JsonConverter using an attribute like [JsonConverter(typeof(MyConverter))]. Is it possible to apply a custom contract resolver on one model in the same way?

在我的场景中,我需要能够在反序列化期间使用[JsonProperty]属性,但在序列化期间忽略它们,仅针对我的一个模型类.

In my scenario, I need to be able to use [JsonProperty] attributes during deserialization but ignore them during serialization, just for one of my model classes.

推荐答案

没有将合同解析器应用于特定模型的属性,因为合同解析器本身负责确定哪些属性适用于模型

There is not an attribute to apply a contract resolver to a specific model, because it is the contract resolver itself that is responsible for determining what attributes apply to the model.

您可以创建一个自定义解析器,该解析器在模型类上查找自定义属性,以确定是否对该类应用特殊行为,并且在没有该属性的情况下,它会恢复为使用默认行为.

You could make a custom resolver which looks for a custom attribute on a model class in order to determine whether to apply special behavior to that class, and in absence of the attribute it reverts to using the default behavior.

但是,我认为这个想法不能很好地解决您的问题,因为您正在使用Web API,并且只希望在序列化而不是反序列化期间应用特殊行为(忽略JsonProperty属性).据我所知,解析器没有办法告诉它正在执行哪个操作.因此,您需要一个自定义的活页夹或格式化程序,以便在适当的时候有选择地应用解析器.

However, I don't think this idea will work well for your scenario because you are using Web API and you only want to apply the special behavior (ignoring JsonProperty attributes) during serialization but not deserialization. As far as I know, the resolver doesn't have a way to tell which operation it is being used for. Therefore you would need a custom binder or formatter to selectively apply the resolver at the appropriate time.

这篇关于通过属性将Contract Resolver应用于特定模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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