JSON.net ContractResolver与JsonConverter [英] JSON.net ContractResolver vs. JsonConverter
问题描述
我已经使用JSON.net已有一段时间了.我已经编写了自定义转换器和自定义合同解析器(通常来自修改S.O.和Newtonsoft网站上的示例),并且它们工作正常.
I've been working with JSON.net for a while. I have written both custom converters and custom contract resolvers (generally from modifying examples on S.O. and the Newtonsoft website), and they work fine.
除了示例之外,挑战是,我几乎看不到何时应该使用一个或另一个(或两者)进行处理的解释.根据我自己的经验,我基本上确定了合同解析器更简单,因此,如果我可以对他们进行所需的工作,那我就走那条路.否则,我将使用自定义JsonConverters.但是,我进一步知道两者有时会一起使用,因此概念变得更加不透明.
The challenge is, other than examples, I see little explanation as to when I should use one or the other (or both) for processing. Through my own experience, I've basically determined that contract resolvers are simpler, so if I can do what I need with them, I go that way; otherwise, I use custom JsonConverters. But, I further know both are sometimes used together, so the concepts get further opaque.
问题:
- 是否存在可以区分何时使用一个用户与另一个用户的来源?我发现Newtonsoft文档不清楚如何区分两者或何时使用一种或另一种.
- 两者之间的订购流程是什么?
推荐答案
好问题.我还没有看到清晰的文档说明您何时应该编写自定义 ContractResolver
或自定义 JsonConverter
解决特定类型的问题.他们确实做着不同的事情,但是每种问题可以解决的问题之间有些重叠.我在回答StackOverflow的问题时写了很多,所以随着时间的流逝,我的情况变得更加清晰了.下面是我的看法.
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 StackOverflow, so the picture has become a little more clear to me over time. Below is my take on it.
合同解析器由Json.Net始终使用 ,并在广泛的水平上管理序列化/反序列化行为.如果设置中未提供自定义解析程序,则 DefaultContractResolver
使用a>.解析器负责确定:
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:
- 每种类型的合同都有什么(即它是原始的,数组/列表,字典,动态的,属性(例如,
[JsonProperty]
,[JsonIgnore]
,[JsonConverter]
等)和 - 这些属性如何影响每个属性(或类)的(反序列化).
- what contract each type has (i.e. is it a primitive, array/list, dictionary, dynamic,
JObject
, plain old object, etc.); - what properties are on the type (if any) and what are their names, types and accessibility;
- what attributes have been applied (e.g.
[JsonProperty]
,[JsonIgnore]
,[JsonConverter]
, etc.), and - how those attributes should affect the (de)serialization of each property (or class).
通常来说,如果您想在广泛的类中自定义序列化或反序列化的某些方面,则可能需要使用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
:
- 更改用于某种类型的合同
- Change the contract used for a type
- Serialize all Dictionaries as an Array of Key/Value Pairs
- Serialize ListItems as a regular object instead of string
- Use camel case for all property names
- Camel case all property names except dictionaries
- Globally use a JsonConverter on a class without the attribute
- Remap properties to different names defined at runtime
- Allow deserializing to public properties with non-public setters
- Optionally turn off the JsonIgnore attribute at runtime
- Make properties which are marked as required (for SOAP) not required for JSON
- Ignore read-only properties across all classes
- Skip serializing properties that throw exceptions
- Encrypt specially marked string properties in any class
- Selectively escape HTML in strings during deserialization
与
ContractResolver
相比,JsonConverter
的焦点更为狭窄:它实际上旨在处理单个类型或相关类型的一小部分的序列化或反序列化.而且,它的工作水平比解析程序低.当转换器负责某种类型的责任时,它可以完全控制该类型的JSON的读取或写入方式:它直接使用JsonWriter
类来完成其工作.换句话说,它可以更改该类型的JSON的 shape .同时,转换器与大图"分离,并且无法访问上下文信息,例如(反序列化的)对象的父级或与其一起使用的属性.以下是一些您可以使用JsonConverter
解决的问题的示例:In contrast to a
ContractResolver
, the focus of aJsonConverter
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 usesJsonReader
andJsonWriter
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 aJsonConverter
:- 处理反序列化中的对象实例化问题
- 反序列化为接口,使用JSON中的信息来确定要实例化的具体类
- 反序列化JSON,它有时是单个对象,有时是对象数组
- 反序列化可以是数组或嵌套数组的JSON
- 从混合类型数组中反序列化时,跳过不需要的项目
- 反序列化为缺少默认构造函数的对象
- Handle object instantiation issues on deserialization
- Deserialize to an interface, using information in the JSON to decide which concrete class to instantiate
- Deserialize JSON that is sometimes a single object and sometimes an array of objects
- Deserialize JSON that can either be an array or a nested array
- Skip unwanted items when deserializing from an array of mixed types
- Deserialize to an object that lacks a default constructor
- 将十进制值序列化为本地化字符串
- 将decimal.MinValue转换为空字符串并返回(用于旧系统)
- 序列化具有多种不同格式的日期
- 反序列化日期时忽略UTC偏移量
- 序列化类型时,使Json.Net调用
ToString()
- Serialize decimal values as localized strings
- Convert decimal.MinValue to an empty string and back (for use with a legacy system)
- Serialize dates with multiple different formats
- Ignore UTC offsets when deserializing dates
- Make Json.Net call
ToString()
when serializing a type
- 将混合值的嵌套数组反序列化为项目列表
- 反序列化具有不同名称的对象数组
- 序列化/反序列化具有复杂键的自定义词典
- 将自定义IEnumerable集合序列化为字典
- 将嵌套的JSON结构放到更简单的对象结构中
- 将简单的对象结构扩展为更复杂的JSON结构
- 将对象列表序列化为仅ID列表
- 将包含GUID的对象的JSON列表反序列化为GUID列表
- Deserialize a nested array of mixed values into a list of items
- Deserialize an array of objects with varying names
- Serialize/deserialize a custom dictionary with complex keys
- Serialize a custom IEnumerable collection as a dictionary
- Flatten a nested JSON structure into a simpler object structure
- Expand a simple object structure into a more complicated JSON structure
- Serialize a list of objects as a list of IDs only
- Deserialize a JSON list of objects containing GUIDs to a list of GUIDs
- Serializing System.Net.IPAddress throws an exception
- Problems deserializing Microsoft.Xna.Framework.Rectangle
这篇关于JSON.net ContractResolver与JsonConverter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- Change the contract used for a type