C#Json.net不可变类 [英] c# Json.net immutable class
问题描述
我看到了其他类似的问题/答案,但均未显示两者序列化/反序列化
I saw other similar questions/answers but none show both serialization/deserialization
示例:
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的严重限制?
This seems be a serious limitation of Json.NET unless I'm missing something ?
推荐答案
@IpsitGaur是正确的,通常,您应该具有默认的公共构造函数和可公共访问的属性(可变).但是JSON.Net是一个非常强大的工具!
@IpsitGaur is right, commonly you should have a default public constructor and publicly accessable properties (mutable). But JSON.Net is a very powerfull tool!
如果您需要处理非默认构造函数,则可以使用 JsonConstructorAttribute .对于您的代码,示例可能像这样:
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);
这篇关于C#Json.net不可变类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!