C# 属性为null的JSON序列化引用异常
考虑以下教程: 对于json代码,我有以下类:C# 属性为null的JSON序列化引用异常,c#,json,properties,nullreferenceexception,javascriptserializer,C#,Json,Properties,Nullreferenceexception,Javascriptserializer,考虑以下教程: 对于json代码,我有以下类: public class Address { public string addressline1 { get; set; } public string addressline2 { get; set; } public string city { get; set; } public string state { get; set; } public string country { get; set; } public int pin
public class Address
{
public string addressline1 { get; set; }
public string addressline2 { get; set; }
public string city { get; set; }
public string state { get; set; }
public string country { get; set; }
public int pin { get; set; }
}
public class RootObject
{
public string firstName { get; set; }
public string lastName { get; set; }
public string department { get; set; }
public Address address { get; set; }
public List<string> technologies { get; set; }
}
它向我抛出nullreferenceexception
。如果我修改行
public List<string> technologies { get;set;}
公共列表技术{get;set;}
按以下路线
public List<string> technologies = new List<string>();
public List technologies=new List();
我不想用。因为我有复杂的JSON类型,不能以这种方式处理。您没有初始化子对象。
address
属性尚未分配address
对象的实例,因此当您尝试更新address1
属性时;应用程序不知道您引用的是哪个对象,因此出现了错误
您只需为地址
属性指定一个值,或使用默认值对其进行初始化
实现这一点的最简单方法是使用RootObject
类的默认构造函数
public class RootObject
{
public RootObject()
{
address = new Address();
technologies = new List<string>();
}
public string firstName { get; set; }
public string lastName { get; set; }
public string department { get; set; }
public Address address { get; set; }
public List<string> technologies { get; set; }
}
公共类根对象
{
公共根对象()
{
地址=新地址();
技术=新列表();
}
公共字符串名{get;set;}
公共字符串lastName{get;set;}
公共字符串部门{get;set;}
公共广播地址{get;set;}
公共列表技术{get;set;}
}
正如@Kami所建议的,您可以在根对象的构造函数中初始化地址
和技术
,或者您可以使用以下语法分配地址行1
(和其他地址
对象的属性):
RootObjectClsObject.address = new Address()
{
addressline1 = "NO"
};
如何声明RootObjectClsObject
变量?正常方式RootObject RootObjectClsObject=new RootObject();谢谢你的信息。但是因为@Kami的解决方案对我的案例更有用。我就选那个。
public class RootObject
{
public RootObject()
{
address = new Address();
technologies = new List<string>();
}
public string firstName { get; set; }
public string lastName { get; set; }
public string department { get; set; }
public Address address { get; set; }
public List<string> technologies { get; set; }
}
RootObjectClsObject.address = new Address()
{
addressline1 = "NO"
};