Is there a way to use Json.Net deserialization with immutable classes?

℡╲_俬逩灬. 提交于 2019-12-30 01:36:13

问题


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?


回答1:


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




回答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.



来源:https://stackoverflow.com/questions/9085676/is-there-a-way-to-use-json-net-deserialization-with-immutable-classes

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