c# - 我在我的 web api 2 中使用 DataContractJsonSerializer 还是 Json.net

标签 c# serialization asp.net-web-api

在问了这个之后question我试图在 web api 2 中掌握所有这些序列化的东西,我读到了这个 http://www.asp.net/web-api/overview/formats-and-model-binding/json-and-xml-serialization

但现在我很困惑

1 在我的 webapiconfig 中我没有这行

var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.UseDataContractJsonSerializer = true;

所以我假设我使用的是默认的 Json.net 序列化程序。无论如何,我仍然可以在类中使用 DataContract,因此只有用 DataMember 属性装饰的属性才会被序列化。这两个假设是否正确?

2 如果我不使用 DataContract 装饰类,所有属性都将被序列化。 Json.net 和 DataContractJsonSerializer 都会发生这种情况

3 如果我更改(如我链接的问题)序列化程序仍然使用它的解析器,是不是因为它是 Json.net 的一个或一件事与另一件事无关?因为如果我在全局中使用它

var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.UseDataContractJsonSerializer = true;
json.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();

即使它没有提出任何问题,它似乎也没有接受它(也不使用自定义契约(Contract)解析器)

3 如果我有一个派生自另一个类的类,并且我用 DataContract 装饰父类,在我看来我必须用 DataMember 装饰子类的属性以对其进行序列化。还是我做错了什么?

谢谢

最佳答案

So I asume I'm using the Json.net serializer which is the defaulted one. Anyway I still can use the DataContract in a class and therefore only the properties decorated with DataMember attribute will be serialized. Are these two assumptions correct?

Json.Net 是默认的,您是对的。两个序列化程序都支持 DataMembers。 Json.Net 不需要它们。

2 If I don't decorate a class with DataContract all of the properties will be serialized. This happen to both the Json.net and the DataContractJsonSerializer

DataContractJsonSerializer 旨在与 WCF 客户端应用程序一起使用,其中序列化类型通常是应用了 DataContract 属性的 POCO 类。没有 DataContract,没有序列化。 WCF 的映射机制使发送和接收变得非常简单,但前提是你的平台是同构的。如果您开始混合使用不同的工具集,您的程序可能会出现问题。

JavaScriptSerializer 可以序列化任何类型,包括匿名类型(一种方式),并且以一种更一致的方式进行。您失去了 WCF 的“自动”功能,但获得了更多集成选项。

3 If I change (as in the question I linked) the resolver the serializer still uses it, is it because it's the Json.net one or one thing is not related to another? because if I use this in the Global

将您的代码放在 Global.asax 中,并且应该使用 DataContractJsonSerializer。你怎么知道它没有被拾起?

4 In case I have a class that derives from another one and I decorate the parent one with DataContract it seems to me that I have to decorate the child one's properties with DataMember for serializing it.

是的。如果您使用 DataContractJsonSerializer。

关于c# - 我在我的 web api 2 中使用 DataContractJsonSerializer 还是 Json.net,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20371040/

相关文章:

c# - C#对象转json字符串,如何处理双引号

Java 记录序列化和对规范构造函数的重复调用

asp.net - Web API 中的 [FromRoute] 和 [FromBody] 有什么区别?

c# - 如何获取请求查询字符串值?

c# - 如何检测 WatiN 中的 Javascript 弹出通知?

c# - MVC 3 将 jquery $.ajax 请求 json 反序列化为对象填充空值而不是空白字符串

c# - 将 RDP 构建到 C# 应用程序中

c# - 如何使用 LINQ 求和?

java - 用java序列化员工列表

c# - WebApi Controller 中使用 SimpleInjector 的运行时空引用异常