Json.net failing to load certain properties belonging to a class object?(Json.net 无法加载属于类对象的某些属性?)
问题描述
注意:我添加此社区 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 只对类的公共成员进行序列化和反序列化.如果您的属性有公共 getter 和私有 setter,那么这些属性将被序列化为 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.
解决此问题的简单方法是将您的 setter 公开,但这当然会破坏私有 setter 提供的不变性.如果您希望在仍然能够反序列化它们的同时保持您的 setter 私有,您可以使用 [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 无法加载属于类对象的某些属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Json.net 无法加载属于类对象的某些属性?
基础教程推荐
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- SSE 浮点算术是否可重现? 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01