Json.net failing to load certain properties belonging to a class object?

二次信任 提交于 2019-12-31 07:24:46

问题


NOTE: I'm adding this community wiki entry to save someone the loss of time I just went through debugging this problem.

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?


回答1:


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.

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.

Here is a short fiddle to demonstrate: https://dotnetfiddle.net/4nZdGJ




回答2:


Although it took me a while to hunt down the problem, the answer was simple. The object properties that always had NULL values when deserialized had private setters. I made the setters public and the problem went away.



来源:https://stackoverflow.com/questions/33704252/json-net-failing-to-load-certain-properties-belonging-to-a-class-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!