更新时间:2023-02-17 21:29:49
好问题.我还没有看到清晰的文档说明您何时应该更喜欢编写自定义 ContractResolver
或自定义 JsonConverter
来解决特定类型的问题.他们确实做不同的事情,但是每个人可以解决的问题类型之间存在一些重叠.在回答 *** 上的问题时,我已经写了很多,所以随着时间的推移,图片对我来说变得更加清晰了.以下是我的看法.
Great question. I haven't seen a clear piece of documentation that says when you should prefer to write a custom ContractResolver
or a custom JsonConverter
to solve a particular type of problem. They really do different things, but there is some overlap between what kinds of problems can be solved by each. I've written a fair number of each while answering questions on ***, so the picture has become a little more clear to me over time. Below is my take on it.
Json.Net始终使用合约解析器,并在广泛的层面上控制序列化/反序列化行为.如果设置中没有提供自定义解析器,则 DefaultContractResolver
被使用.解析器负责确定:
A contract resolver is always used by Json.Net, and governs serialization / deserialization behavior at a broad level. If there is not a custom resolver provided in the settings, then the DefaultContractResolver
is used. The resolver is responsible for determining:
JObject
,普通旧对象等);[JsonProperty]
、[JsonIgnore]
、[JsonConverter]
等)、JObject
, plain old object, etc.); [JsonProperty]
, [JsonIgnore]
, [JsonConverter]
, etc.), and 一般来说,如果您想跨范围广泛的类自定义序列化或反序列化的某些方面,您可能需要使用 ContractResolver
来完成.以下是您可以使用 ContractResolver
自定义的一些示例:
Generally speaking, if you want to customize some aspect of serialization or deserialization across a wide range of classes, you will probably need to use a ContractResolver
to do it. Here are some examples of things you can customize using a ContractResolver
:
与 ContractResolver
相比,JsonConverter
的关注点更窄:它真正旨在处理单个类型或一小部分的序列化或反序列化相关类型.此外,它的工作级别低于解析器.当转换器负责一个类型时,它可以完全控制如何读取或写入该类型的 JSON:它直接使用 JsonReader
和 JsonWriter
类来完成它的工作.换句话说,它可以更改该类型的 JSON 的 shape.同时,转换器与大图"分离,并且无法访问上下文信息,例如正在(反)序列化的对象的父级或与它一起使用的属性属性.以下是您可以使用 JsonConverter
解决的一些问题示例:
In contrast to a ContractResolver
, the focus of a JsonConverter
is more narrow: it is really intended to handle serialization or deserialization for a single type or a small subset of related types. Also, it works at a lower level than a resolver does. When a converter is given responsibility for a type, it has complete control over how the JSON is read or written for that type: it directly uses JsonReader
and JsonWriter
classes to do its job. In other words, it can change the shape of the JSON for that type. At the same time, a converter is decoupled from the "big picture" and does not have access to contextual information such as the parent of the object being (de)serialized or the property attributes that were used with it. Here are some examples of problems you can solve with a JsonConverter
:
ToString()