jeudi 27 juillet 2023

weird Json deserialization on a read-only property in C#

Can somebody explain how does it work? I even use reflection to set value to B, but it said B dont have a set value. How Newtonsoft.Json make this work?

public class A
{
    private int a = 10;
    public int B => a;
}

var a = new A();
var json = JsonConvert.SerializeObject(a);//json={"B":10}

//my expectation: this will have error, because B only have getter, dont have setter
//in reality: this run OK, and aa.B = aa.a = 10
var aa = JsonConvert.DeserializeObject<A>(json);




Aucun commentaire:

Enregistrer un commentaire