有没有办法将 Json.Net 反序列化与不可变类一起使用?

发布于 2025-01-01 16:29:47 字数 179 浏览 2 评论 0原文

我正在使用一个使用 json 的 API。我创建了一些类来对 API 进行建模。为了让生活变得简单,我的模型使用公共属性,Json.Net 在将 json 反序列化为对象时又会使用这些公共属性。

我想让我的对象不可变,但我遇到了一个问题,因为如果我将属性设为只读,就会破坏反序列化。有没有办法让我拥有不可变的对象并使用反序列化?

I'm working with an API that uses json. I have some classes that I've created to model the API. To make life easy, my models use public properties, which are in turn used by Json.Net when deserializing the json into objects.

I'd like to make my objects immutable, but I'm running into a problem because if I make my properties read only, I break the deserialization. Is there a way for me to have immutable objects, and use deserialization?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

月竹挽风 2025-01-08 16:29:47

提供一个带有与属性相对应的参数的构造函数。参数和属性的首字母大小写不需要匹配。

Provide a constructor with parameters that correspond to the properties. The casing of the first letters of the parameters and properties does not need to match.

清晨说晚安 2025-01-08 16:29:47

I think you should be able to use JsonConstructorAttribute. See this question for an example.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文