0

NOTE: I'm adding this community wiki entry to save someone the loss of time I just went through debugging this problem.

I have a class object with multiple public properties. I can serialize it fine using JSON.net. But when I load the JSON text back and deserialize it using JsonConvert.DeserializeObject<>, some of the fields are set to NULL when they definitely had valid values at the time of serialization. I inspected the serialized JSON string manually and I definitely see values for the NULL properties in the text. Why is this happening?

Racil Hilan
  • 24,690
  • 13
  • 50
  • 55
Robert Oschler
  • 14,153
  • 18
  • 94
  • 227

2 Answers2

3

By default, Json.Net serializes and deserializes only the public members of a class. If you have public getters but private setters for your properties then the properties will be serialized to JSON but not deserialized back to your class.

The easy way to fix this is to make your setters public, but of course that breaks the immutability that private setters provide. If you want to be able to keep your setters private while still being able to deserialize them, you can annotate your properties with [JsonProperty] attributes instead. This will allow the deserializer to "see" them.

Here is a short fiddle to demonstrate: https://dotnetfiddle.net/4nZdGJ

Brian Rogers
  • 125,747
  • 31
  • 299
  • 300
0

Although it took me a while to hunt down the problem, the answer was simple. The object properties that always had NULL values when deserialized had private setters. I made the setters public and the problem went away.

Robert Oschler
  • 14,153
  • 18
  • 94
  • 227
  • 2
    If you want to keep your setters private, you can annotate your class properties with `[JsonProperty]` attributes and that will allow the deserializer to "see" them. – Brian Rogers Nov 14 '15 at 03:15
  • Thanks Brian. That's a great tip. If you turned that comment into an answer I'd mark it as the accepted answer since it's better than mine. – Robert Oschler Nov 15 '15 at 17:21