JsonConvert.DeserializeObject反序列化无法赋值和空引用异常问题

如下立方体类

public class Point
{
    private int x, y, z;
    public int X { get { return x; } set { x = value; } }
    public int Y { get { return y; } set { y = value; } }
    public int Z { get { return z; } set { z = value; } }
    public Point(int xx, int yy, int zz) { x = xx; y = yy; z = zz; }
}

public class Cube
{
    private Point point;
    private int length, weight, high;
    public int Length{ get{ return length;}}
    public int Weight{ get{ return weight;};}
    public int High{ get{ return high;}}
    public Point Point { get { return point; } }
    public Cube(Point p , int l, int w, int h)
    {
        point = p;
        length = l; weight = w; high = h;
    }
}

Cube cube = JsonConvert.DeserializeObject<Cube>(json)

使用cube.Point系统会提示
NullReferenceException: Object reference not set to an instance of an object
即未将引用对象实例化,或者使用cube.Length时数据永远为0,同理cube.Weight和cube.High。
这是由于JsonConvert.DeserializeObject生成类时,首先调用类的无参构造函数,若未定义类的无参构造函数,则会调用系统默认无参构造函数,再进行赋值。
但由于未给Cube定义无参构造函数,所以,生成类时,不会生成Cube的子类Point,即调用Point就会引起引用异常。同样,Json反序列化赋值时,若为给私有成员设置赋值接口,JsonConvert就会无法赋值使得Length等始终为0。

解决问题只需将类的定义改为一下参考即可:

public class Point
{
    private int x, y, z;
    public int X { get { return x; } set { x = value; } }
    public int Y { get { return y; } set { y = value; } }
    public int Z { get { return z; } set { z = value; } }
    public Point(int xx, int yy, int zz) { x = xx; y = yy; z = zz; }
    public Point() { x = 0; y = 0; z = 0; }
}

public class Cube
{
    private Point point;
    private int length, weight, high;
    public int Length{ get{ return length; } set { length = value; } }
    public int Weight{ get{ return weight; } set { weight = value; } }
    public int High{ get{ return high; } set { high = value; } }
    public Point Point { get { return point; } }
    public Cube(Point p , int l, int w, int h)
    {
        point = p;
        length = l; weight = w; high = h;
    }
    public Cube()
    {
    	point = new Point();
        length = 0; weight = 0; high = 0;
    }
}

你可能感兴趣的:(C#,c#)