[英]Json.Net roundtrip fails with PascalCase
The following class will roundtrip (serialize to string, then deserialize to object) just fine: 下面的类将进行往返(序列化为字符串,然后反序列化为对象)就可以了:
public class FoobarObject
{
public readonly IFileLocation File1;
public readonly IFileLocation File2;
public readonly IFileLocation File3;
public FoobarObject(IFileLocation file1, IFileLocation file2, IFileLocation file3)
{
File1 = file1;
File2 = file2;
File3 = file3;
}
}
However, if I change it to the following, it will fail (the fields are returned as null
): 但是,如果我将其更改为以下内容,它将失败(字段返回为null
):
public class FoobarObject
{
//[JsonProperty("SomeFile1")]
public readonly IFileLocation SomeFile1;
public readonly IFileLocation File2;
public readonly IFileLocation File3;
public FoobarObject(IFileLocation file1, IFileLocation file2, IFileLocation file3)
{
SomeFile1 = file1;
File2 = file2;
File3 = file3;
}
}
But, by uncommenting the JsonProperty
line, the object will roundtrip properly. 但是,通过取消注释JsonProperty
行,对象将正确往返。
The serialized string appears to be correct ( "{\\"SomeFile1\\":\\"C:\\\\\\\\vibwd541.u2q\\\\\\\\Foobar1\\", \\"File2\\":\\"C:\\\\\\\\vibwd541.u2q\\\\\\\\Foobar2\\", \\"File3\\":null}"
, but the deserializing does not happen. 序列化的字符串似乎正确( "{\\"SomeFile1\\":\\"C:\\\\\\\\vibwd541.u2q\\\\\\\\Foobar1\\", \\"File2\\":\\"C:\\\\\\\\vibwd541.u2q\\\\\\\\Foobar2\\", \\"File3\\":null}"
,但是不会发生反序列化。
What is going on? 到底是怎么回事?
The reason this is happening is that, by default, Json.NET uses the ConstructorHandling.Default algorithm to determine the constructor to use when deserializing a type. 发生这种情况的原因是,默认情况下,Json.NET使用ConstructorHandling.Default算法来确定反序列化类型时要使用的构造函数。 This algorithm works as follows, according to the docs : 根据docs ,此算法的工作原理如下:
ConstructorHandling Enumeration 构造函数处理枚举
Default First attempt to use the public default constructor, then fall back to single paramatized constructor, then the non-public default constructor. AllowNonPublicDefaultConstructor Json.NET will use a non-public default constructor before falling back to a paramatized constructor.
Your class has a single public constructor. 您的课程只有一个公共构造函数。 It has three parameters IFileLocation file1, IFileLocation file2, IFileLocation file3
. 它具有三个参数IFileLocation file1, IFileLocation file2, IFileLocation file3
。 Thus Json.NET will use it to construct your object during deserialization, matching JSON property names to constructor parameter names using reflection . 因此,Json.NET将在反序列化期间使用它来构造您的对象, 并使用reflection将JSON属性名称与构造函数参数名称匹配 。 So if you rename File1
to SomeFile1
during serialization it will no longer match the name of any of the constructor arguments, and will not be deserialized. 所以,如果您重命名File1
至SomeFile1
序列化过程中,将不再匹配任何的构造函数的参数名称,而不会被反序列化。
To avoid this problem, make sure that the property names match the constructor argument names. 为避免此问题,请确保属性名称与构造函数参数名称匹配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.