Applying a Contract Resolver to a specific model via an attribute

ぃ、小莉子 提交于 2019-12-25 09:45:21

问题


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?

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.


回答1:


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.

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.



来源:https://stackoverflow.com/questions/43820249/applying-a-contract-resolver-to-a-specific-model-via-an-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!