2

我正在努力解决这个论坛中有很多变体的主题,但我似乎找不到适合我的主题,我认为这是因为我的 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”类中的值?这是我走的最远...

4

1 回答 1

3

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

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;
于 2013-05-16T04:20:47.977 回答