Deserialize read-only variables
Asked Answered
A

3

8

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?

Amortization answered 1/10, 2015 at 13:16 Comment(2)
Don't make it readonly?Synectics
Profile picture checks out.Trivalent
B
16

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)
Budde answered 1/10, 2015 at 13:27 Comment(0)
S
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.

Synectics answered 1/10, 2015 at 13:21 Comment(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.Amortization
S
0

You can add [JsonObject(MemberSerialization.Fields)] on top of the class, so any field will be serialized, including private and readonly ones.

To exclude field from serialization, use[JsonIgnore]

Suanne answered 6/4 at 17:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.