0

考虑以下教程: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 无法以这种方式处理。

4

2 回答 2

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; }
}
于 2013-01-14T11:24:03.440 回答
1

正如@Kami 建议的那样,您可以在的构造函数中初始化addressand ,或者您可以使用以下语法分配(和其他对象的属性):technologiesRootObjectaddressline1address

RootObjectClsObject.address = new Address()
{
    addressline1 = "NO"
};
于 2013-01-14T11:45:25.407 回答