问题
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