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?

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.