7

I have class like this:

public class Pussy {
    public readonly int Meows;

    [JsonConstructor]
    private Pussy() { }

    public Pussy(int meows)
    {
        this.Meows = meows;
    }
}

When I'm trying to serialize it with Json.NET, it working fine:

{"Meows":3}

But when deserialize, it's just creating class with Meows set to 0.

What's wrong? How to fix it?

Shamil Yakupov
  • 5,409
  • 2
  • 16
  • 21

2 Answers2

15

Try to use JsonProperty attribute for readonly fields

[JsonProperty]
public readonly int Meows;

Or JsonConstructor attribute for non-default ctor.

[JsonConstructor]
public Pussy(int meows)
oakio
  • 1,868
  • 1
  • 14
  • 21
0

Deserializers in general take the requested type and inspect the publicly settable fields and properties using reflection.

Your field is not publicly settable, so it will not be written to during deserialization.

To fix it, remove the readonly modifier.

Or you could create a custom resolver and/or serializer that writes to readonly fields using reflection.

Community
  • 1
  • 1
CodeCaster
  • 147,647
  • 23
  • 218
  • 272
  • 1
    Yea, as variant, I can remove `readonly`, but this field should not be edited after construction. It's worked with JavaScriptSerializer and now not with Json.NET. – Shamil Yakupov Oct 01 '15 at 13:28