2

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.

Franz Gsell
  • 1,425
  • 2
  • 13
  • 22
  • 1
    Can you post the code showing how you deserialize it? Assuming you're deserializing to the correct type (with the correct type parameter) it should be fine. – Reinstate Monica Cellio May 17 '19 at 07:37
  • 2
    `{ get; }` is the `set;` missing? – xdtTransform May 17 '19 at 07:47
  • 2
    Your property has no setter. It's possible to deserialize a read-only property if you have an appropriate parameterized constructor. See [Private setters in Json.Net](https://stackoverflow.com/q/4066947) and [JSON.net: how to deserialize without using the default constructor?](https://stackoverflow.com/q/23017716) and [How does JSON deserialization in C# work](https://stackoverflow.com/a/41871975/3744182). Need to see a [mcve] to know your real problem. – dbc May 17 '19 at 07:49
  • @dbc, Was looking for one of those. But those 3 are great. You can make them multiple dupe target. It's a lot better than a typo closure. And Really clear solution in 1-2 and explanation in the 3rd one. – xdtTransform May 17 '19 at 08:06

0 Answers0