38

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?

GregB
  • 5,465
  • 5
  • 23
  • 35

2 Answers2

24

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.

Edward Brey
  • 40,302
  • 20
  • 199
  • 253
22

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

Community
  • 1
  • 1
Matthew Flaschen
  • 278,309
  • 50
  • 514
  • 539