gpt4 book ai didi

c# - 如何反序列化列表中的 JSON 数组 (C#)

转载 作者:行者123 更新时间:2023-11-30 22:17:46 26 4
gpt4 key购买 nike

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

最佳答案

我从您的问题中复制的以下代码正在创建一个与您的反序列化数据无关的全新列表。因此,它始终是单个元素列表,其中第一个元素仅包含默认值,这就是您稍后在 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;

关于c# - 如何反序列化列表中的 JSON 数组 (C#),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16578137/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com