使用Properties null引用异常的JSON序列化

时间:2013-01-14 11:02:02

标签: c# json properties nullreferenceexception javascriptserializer

考虑以下教程:http://blogs.msdn.com/b/rakkimk/archive/2009/01/30/asp-net-json-serialization-and-deserialization.aspx

{
    "firstName" : "Rakki",
    "lastName" : "Muthukumar",
    "department" : "Microsoft PSS",
    "address" : {
        "addressline1" : "Microsoft India GTSC",
        "addressline2" : "PSS - DSI",
        "city" : "Bangalore",
        "state" : "Karnataka",
        "country" : "India",
        "pin" : 560028
    },
"technologies" : ["IIS", "ASP.NET", "JavaScript", "AJAX"]    
}

对于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 { 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; }
}

当我尝试设置

等数据时,上述属性会给我错误
RootObjectClsObject.address.addressline1 = "NO";

它引发了我NullReferrenceException。如果我修改了行

public List<string> technologies { get;set;}

通过以下行

public List<string> technologies = new List<string>();

我不想使用。因为我有复杂类型的JSON,无法以这种方式处理。

2 个答案:

答案 0 :(得分:1)

您没有初始化子对象。尚未为address属性分配Address对象的实例,因此当您尝试更新address1属性时;应用程序不知道您指的是哪个对象 - 因此错误。

您只需要为address属性分配值或使用默认值对其进行初始化。

执行此操作的最简单方法是使用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; }
}

答案 1 :(得分:1)

正如@Kami建议的那样,您可以在address的构造函数中初始化technologiesRootObject,或者您可以指定addressline1(以及其他{{} 1}} object的属性)使用以下语法:

address