【发布时间】:2017-01-26 09:15:53
【问题描述】:
我试图了解JsonConvert.DeserializeObject<X>(someJsonString) 是如何使用构造函数设置值的。
using Newtonsoft.json
public class X {
[JsonProperty("some_Property")]
public string SomeProperty {get;}
[JsonProperty("some_Property_2")]
public string SomeProperty2 {get;}
public X(string someProperty, string someProperty2) {
SomeProperty = someProperty;
SomeProperty2 = someProperty2;
}
public static X parseObject(string parseThisJson) {
JsonConvert.DeserializeObject<X>(someJsonString);
}
}
在上面的代码中,我想了解 JsonConvert.DeserializeObject 是如何正确反序列化它的。
json 序列化是否使用此 public X(string someProperty, string someProperty2) 构造函数?如果是这样,这个构造函数是如何调用和使用的?
如果 parseThisJson 除了 some_Property 和 some_Property_2 之外还有更多的键值对会发生什么?
【问题讨论】:
-
您可以在 1 分钟内检查。在构造函数中设置断点
-
不完全是,这取决于序列化/反序列化的实际类型。 XmlSerialization 例如 does 使用默认构造函数。然而,这对这里的实际问题毫无意义。
-
你知道它是开源的,你可以在github上查看它对吗?
-
构造函数中未出现的属性值仍将使用 PropertyInfo.SetValue() 设置。 msdn.microsoft.com/en-us/library/…
-
查看 Avoiding default constructors and public property setters 了解 Json.NET 的作用。基本上,它确实在参数化构造函数是唯一要调用的构造函数时使用它,或者它被标记为
[JsonConstructorAttribute],并按名称模大小写匹配JSON属性的参数。