问题描述
注意:我添加此社区Wiki条目是为了节省某人我刚刚调试此问题所花费的时间.
NOTE: I'm adding this community wiki entry to save someone the loss of time I just went through debugging this problem.
我有一个具有多个公共属性的类对象.我可以使用JSON.net对其进行序列化.但是,当我重新加载JSON文本并使用JsonConvert.DeserializeObject<>
反序列化时,当某些字段在序列化时确实具有有效值时,会将它们设置为NULL
.我手动检查了序列化的JSON字符串,并且在文本中肯定看到了NULL属性的值.为什么会这样?
I have a class object with multiple public properties. I can serialize it fine using JSON.net. But when I load the JSON text back and deserialize it using JsonConvert.DeserializeObject<>
, some of the fields are set to NULL
when they definitely had valid values at the time of serialization. I inspected the serialized JSON string manually and I definitely see values for the NULL properties in the text. Why is this happening?
推荐答案
默认情况下,Json.Net仅序列化和反序列化类的公共成员.如果您的属性具有公共获取器但私有设置器,则这些属性将被序列化为JSON,但不会反序列化回您的类.
By default, Json.Net serializes and deserializes only the public members of a class. If you have public getters but private setters for your properties then the properties will be serialized to JSON but not deserialized back to your class.
解决此问题的简单方法是公开您的设置员,但是这当然打破了私人设置员提供的不变性.如果希望保留设置程序的私密性,同时又可以反序列化它们,则可以使用[JsonProperty]
属性来注释属性.这将使解串器可以看到"它们.
The easy way to fix this is to make your setters public, but of course that breaks the immutability that private setters provide. If you want to be able to keep your setters private while still being able to deserialize them, you can annotate your properties with [JsonProperty]
attributes instead. This will allow the deserializer to "see" them.
这里有一个简短的小提琴来演示: https://dotnetfiddle.net/4nZdGJ
Here is a short fiddle to demonstrate: https://dotnetfiddle.net/4nZdGJ
这篇关于Json.net无法加载属于类对象的某些属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!