如何反序列化List中的JSON数组(C#)

时间:2013-05-16 02:38:03

标签: c# json deserialization

我正在努力研究这个论坛中有很多变种的主题,但我似乎无法找到一个适合我的主题,而且我认为这是因为我的JSON数组的方式:( 我不是专家,但我已经设法“差点”结束...... 我需要获得“成功”和“状态”价值。但也有不同的“地址”。

我的JSON(称为responseFromServer):

{
  "success":true,
  "addresses":
  [
   {"DPID":658584,"SourceDesc":"Postal\\Physical","FullAddress":"1/8 Jonas Street, Waimataitai, Timaru 7910"},
   {"DPID":658585,"SourceDesc":"Postal\\Physical","FullAddress":"2/8 Jonas Street, Waimataitai, Timaru 7910"},
   {"DPID":658583,"SourceDesc":"Postal\\Physical","FullAddress":"3/8 Jonas Street, Waimataitai, Timaru 7910"}
  ],
 "status":"success"
}

然后,基于这个论坛中的很多例子,我创建了我的课程:

public class jsonDataTable
{
    public bool success { get; set; }
    public IEnumerable<dtaddresses> addresses { get; set; }
    public string status { get; set; }
}

public class dtaddresses 
{
    public int DPID { get; set; }
    public string SourceDesc { get; set; }
    public string FullAddress { get; set; }
}

然后我要反序列化:

public void _form_OnCallingAction(object sender, ActionEventArgs e)
{
 ...
 ...
 JavaScriptSerializer js = new JavaScriptSerializer();
 jsonDataTable jsonArray = js.Deserialize<jsonDataTable>(responseFromServer);
 ...
 string tb = jsonArray.status.ToString();
 string tb2 = jsonArray.success.ToString();
 ...
 ...
 List<dtaddresses> _listAddresses = new List<dtaddresses>
 {
  new dtaddresses()
 };
 ...
 ...
 try
 {
  string tb3 = _listAddresses.Count.ToString();
  string tb4 = _listAddresses[0].FullAddress;
 }
 catch (Exception ex)
 {
  CurrentContext.Message.Display(ex.Message + ex.StackTrace);
 }
...
...
...
 CurrentContext.Message.Display("Raw Response from server is: {0}", responseFromServer);
 //Returns all the content in a string to check. OK! :)

 CurrentContext.Message.Display("The success value is: {0} ", tb);
 //Returns the Status Value (in this case "success")  OK! :)

 CurrentContext.Message.Display("The status value is: {0} ", tb2);
 //Returns the Success Value (in this case "true")  giggity giggity! All Right! :)

 CurrentContext.Message.Display("The n. of addresses is: {0} ", tb3);
 //Returns how many addresses ( in this case is returning 0) not ok... :(

 CurrentContext.Message.Display("The address value is: {0} ", tb4);
 // Returns the Fulladdress in index 0 (in this case nothing...) not ok... :(

任何人都可以帮助我理解为什么我可以访问“dtaddresses”类中的值吗? 这是我走的远......

1 个答案:

答案 0 :(得分:3)

我从您的问题中复制的以下代码是创建一个与您的反序列化数据无关的全新列表。因此,它始终是单个元素列表,其中第一个元素仅包含默认值,这是您在tb3tb4中看到的内容。

List<dtaddresses> _listAddresses = new List<dtaddresses>
{
 new dtaddresses()
};

而是将jsonArray.addresses分配给_listAddresses,例如:

List<dtaddresses> _listAddresses = jsonArray.addresses.ToList() 

或者您可以完全忘记_listAddresses,只需直接引用jsonArray.addresses,例如:

string tb3 = jsonArray.addresses.Count().ToString();
string tb4 = jsonArray.addresses.First().FullAddress;