I have a class with a property:
[JsonProperty]
public T MyValue { get; }
The "MyValue" is for example an integer value during runtime. The serialization is done like this:
var data = JsonConvert.SerializeObject(myobj, new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.Auto
});
File.WriteAllText(fileName, data);
My JSON looks like this:
{
"MyValue": 64110,
},
And after the deserialization the MyValue property is always "0" and not the expected value.
Solution:
Thanks to the comments below the solution was really to add a "private set;". I upgraded my projects and forgot to add this. It seems with C# 6 no setter is not equivalent to "private set". see below (a comment from @emragins):
With c# 6, {get; } is NOT equivalent to { get; private set; }. For the first way property.GetSetMethod(true) returns null and the latter true. This surprised me. You must have private set; for deserialization to work as expected.