当我尝试反序列化 JSON 时我遇到错误,因为我的 JSON 不是单个数据(就像数组),然后我尝试使用 List<>
但它说Cannot convert from System.Collections.Generic.List<string>' to 'string
以下是 JSON 数据的示例:
[
{
"no":"73",
"nama":"Nicosia Lady",
"uk":"37 - 40",
"fotou":"73-u.jpg",
"bahan":"Canvas",
"poin":"120",
"harga":"119900.00",
"warna1":"Green",
"warna2":"Grey",
"warna3":"Navy",
"warna4":"Maroon",
"warna5":null
},
{
"no":"78",
"nama":"Minsk Man",
"uk":"38 - 43",
"fotou":"78-u.jpg",
"bahan":"Canvas",
"poin":"140",
"harga":"141800.00",
"warna1":"Black White",
"warna2":"Brown BCoffee",
"warna3":"Navy Orange",
"warna4":"Grey Navy",
"warna5":null
},
]
这是我的班级:
class user
{
public int no { get; set; }
public string nama { get; set; }
public string uk { get; set; }
public string fotou { get; set; }
public string bahan { get; set; }
public int poin { get; set; }
public int harga { get; set; }
public string warna1 { get; set; }
public string warna2 { get; set; }
public string warna3 { get; set; }
public string warna4 { get; set; }
public string warna5 { get; set; }
}
这是脚本:
button.Click += async (sender, e) =>
{
string url = "http://myapi.com/url/example/";
List<user> userList = JsonConvert.DeserializeObject<List<user>>(await FetchUserAsync(url));//got error on await FetchUserAsync(url)
// txtHasil.Text = userList.nama;
};
而这个:
private async Task<List<string>> FetchUserAsync(string url)
{
// Create an HTTP web request using the URL:
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));
//HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.ContentType = "application/json";
request.Method = "GET";
// Send the request to the server and wait for the response:
using (WebResponse response = await request.GetResponseAsync())
{
// Get a stream representation of the HTTP web response:
using (var sr = new StreamReader(response.GetResponseStream()))
{
string strContent = sr.ReadToEnd();
return strContent;// got error on this line
}
}
}
返回string
而不是List<string>
。
另一个更正(但不是错误)将 int 更改为字符串,因为您将获得以下属性的字符串值:
public string no { get; set; }
public string poin { get; set; }
public string harga { get; set; }