Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialize read-only variables

Tags:

c#

json.net

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?

like image 708
Shamil Yakupov Avatar asked Oct 01 '15 13:10

Shamil Yakupov


1 Answers

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)
like image 196
oakio Avatar answered Oct 05 '22 03:10

oakio