繁体   English   中英

C#Json.net不可变类

[英]c# Json.net immutable class

我看到其他类似的问题/答案,但没有显示这两个序列化/反序列化

例:

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);
    }
}

我在DeepNested.DeepNested(DeepNested dn)DeepNested.DeepNested(DeepNested dn)异常

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

调试器显示dn为null

除非我缺少某些东西,否则这似乎是Json.NET的严重限制。

@IpsitGaur是正确的,通常您应该具有默认的公共构造函数和可公共访问的属性(可变)。 但是JSON.Net是一个非常强大的工具!

如果需要处理非默认构造函数,则可以使用JsonConstructorAttribute 对于您的代码,示例可能像这样:

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);

以下作品...

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);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM