c# Json.net immutable class

故事扮演 提交于 2021-02-08 07:39:45

问题


I saw other similar questions/answers but none show both serialization/deserialization

Example:

public class DeepNested {
    [JsonProperty]
    int X { get; }

    [JsonProperty]
    int Y { get; }

    public DeepNested(int x, int y) { X = x; Y = y; }

    [JsonConstructor]
    public DeepNested(DeepNested dn) { X = dn.X; Y = dn.Y; }
}

public class Nested {
    [JsonProperty]
    DeepNested DN { get; }

    [JsonProperty]
    int Z { get; }

    [JsonProperty]
    int K { get; }

    [JsonConstructor]
    public Nested(DeepNested dn, int z, int k) { DN = new DeepNested(dn); Z = z; K = k; }
}

public class C {
    [JsonProperty]
    Nested N { get; }

    [JsonConstructor]
    public C(Nested n) { N = n; }
}

class Program {
    static void Main(string[] args) {
        var deepNested = new DeepNested(1,2);
        var nested = new Nested(deepNested, 3, 4);
        C c = new C(nested);
        string json = JsonConvert.SerializeObject(c);
        C c2 = JsonConvert.DeserializeObject<C>(json);
        Console.WriteLine(json);
    }
}

I get an exception on DeepNested.DeepNested(DeepNested dn)

System.NullReferenceException: 'Object reference not set to an instance of an object.'

The debugger shows dn is null

This seems be a serious limitation of Json.NET unless I'm missing something ?


回答1:


@IpsitGaur is right, commonly you should have a default public constructor and publicly accessable properties (mutable). But JSON.Net is a very powerfull tool!

If you need to handle non-default constructor, you may use JsonConstructorAttribute. For your code, example may be like this:

public class Nested
{
    public int X { get; }
    public int Y { get; }

    [JsonConstructor]
    Nested(int x, int y) { X=x; Y=y; }
}

public class C
{
    public Nested N { get; }

    [JsonConstructor]
    public C(Nested n) { N = n; }
}

var c1 = new C(new Nested(1, 2));
var json = JsonConvert.SerializeObject(c1); // produce something like "{\"n\":{\"x\":1,\"y\":2}}";
var c2 = JsonConvert.DeserializeObject<C>(json);



回答2:


The following works...

public class Nested
{
    [JsonProperty]
    int X { get; }

    [JsonProperty]
    int Y { get; }

    public Nested(int x, int y) { X = x; Y = y; }
}

public class C
{
    [JsonProperty]
    Nested N { get; }

    public C(Nested n) { N = n; }
}

class Program
{
    static void Main(string[] args)
    {
        Nested nested = new Nested(1, 2);
        C c = new C(nested);
        string json = JsonConvert.SerializeObject(c);
        C c2 = JsonConvert.DeserializeObject<C>(json);
    }
}


来源:https://stackoverflow.com/questions/51202726/c-sharp-json-net-immutable-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!