C#Json.net不可变类

时间:2018-07-06 03:46:28

标签: c# json.net

我看到了其他类似的问题/答案,但均未显示两者序列化/反序列化

示例:

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)上遇到异常

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

调试器显示dn是null

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

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

以下作品...

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