问题
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