JSON.net ContractResolver与JsonConverter [英] JSON.net ContractResolver vs. JsonConverter

查看:115
本文介绍了JSON.net ContractResolver与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.

问题:

  1. 是否存在可以区分何时使用一个用户与另一个用户的来源?我发现Newtonsoft文档不清楚如何区分两者或何时使用一种或另一种.
  2. 两者之间的订购流程是什么?

推荐答案

好问题.我还没有看到清晰的文档说明您何时应该编写自定义 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 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:

  • 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:

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