有没有办法将 Json.Net 反序列化与不可变类一起使用?
我正在使用一个使用 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
提供一个带有与属性相对应的参数的构造函数。参数和属性的首字母大小写不需要匹配。
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.
我认为您应该能够使用
JsonConstructorAttribute
< /a>.有关示例,请参阅此问题。I think you should be able to use
JsonConstructorAttribute
. See this question for an example.