Json.net 无法加载属于类对象的某些属性? [英] Json.net failing to load certain properties belonging to a class object?

查看:22
本文介绍了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 无法加载属于类对象的某些属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆