[英]C# ASP.NET MVC convert string to list using JSON
I have an application where I am receiving a datafeed.我有一个应用程序正在接收数据馈送。 The data looks like this after the code below is executed, the variable 'result' looks like this:
执行以下代码后数据如下所示,变量“result”如下所示:
[
{
"personName": "Avery Davis",
"personOrganization": "01"
},
{
"personName": "Chris Davis",
"personOrganization": "01"
},
{
"personName": "Tony Davis",
"personOrganization": "01"
},
{
"personName": "Cory Dirt",
"personOrganization": "01"
},
{
"personName": "Tyler Dirt",
"personOrganization": "01"
},
{
"personName": "Ann Ford",
"personOrganization": "01"
},
{
"personName": "Lauren Ford",
"personOrganization": "01"
},
{
"personName": "Lauren Ford",
"personOrganization": "01"
},
{
"personName": "Avery Franklin",
"personOrganization": "01"
}
]
I have a model class which looks like this:我有一个 model class 看起来像这样:
public class AllPeople
{
public List<PeopleList> data { get; set; }
}
public class PeopleList
{
public string personName { get; set; }
public string personOrganization { get; set; }
}
This is the code that I use to retrieve the data:这是我用来检索数据的代码:
private IEnumerable<PeopleList> GetPeople()
{
IEnumerable<PeopleList> peopleLists = null;
var client = new WebClient();
var data = client.DownloadData("https://localhost:44314/api/values");
var stream = new MemoryStream(data);
var obj = new DataContractJsonSerializer(typeof(string));
var result = obj.ReadObject(stream).ToString();
peopleLists = (IEnumerable<PeopleList>)JsonConvert.DeserializeObject<AllPeople>(result);
return peopleLists;
}
I know the JsonConvert
line is incorrect but I have been unsuccessful in figuring out how to convert the string into a list.我知道
JsonConvert
行不正确,但我一直未能弄清楚如何将字符串转换为列表。
Any suggestions?有什么建议么?
Thanks.谢谢。
In the JSON shown there's no property called data
.在显示的 JSON 中,没有名为
data
的属性。 So this isn't an instance of AllPeople
.所以这不是
AllPeople
的一个实例。 The JSON shown is just an array of PeopleList
.显示的 JSON 只是
PeopleList
的数组。 (Which, incidentally, is a terrible name for a single instance of a "person" .) (顺便说一下,对于“人”的单个实例来说,这是一个可怕的名字。)
Deserialize it to a List<PeopleList>
:将其反序列
List<PeopleList>
:
peopleLists = JsonConvert.DeserializeObject<List<PeopleList>>(result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.