我试图用一些API数据填充组合框,但JSON出现问题。
API调用:
string URL = @"https://localhost:44306/api/user/68/all";
Uri Urladdress = new Uri(URL);
HttpWebRequest request = WebRequest.Create(Urladdress) as HttpWebRequest;
request.Headers["X-AccessToken"] = AccessToken;
request.Method = "GET";
request.ContentType = "application/json";
string results = string.Empty;
HttpWebResponse response;
using (response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
results = reader.ReadToEnd();
}
List<Json> lsObj = JsonConvert.DeserializeObject<List<Json>>(results);
foreach (Json obj in lsObj)
{
for (int i = 0; i < obj.Users.Count(); i++)
{
friends.Items.Add(obj.Users[i].UserId);
}
}
JSON类:
public class Json
{
public List<User> Users { get; set; }
}
public class User
{
public int UserId { get; set; }
public string Username { get; set; }
public string FullName { get; set; }
public object Password { get; set; }
}
API响应:
{"Users":[{"UserId":68,"Username":"Rob","FullName":"Rob test","Password":null},{"UserId":69,"Username":"Test","FullName":"TestRob","Password":null}]}
Visual Studio在UserId的obj.Users.UserId上返回错误
'User []'不包含'UserID'的定义,并且不可访问 扩展方法'UserId'接受类型为'User []'的第一个参数 可以找到(您是否缺少using指令或程序集 参考?)
是否有解决此问题的简单方法?
答案 0 :(得分:0)
您正试图从集合Users中访问User属性,请尝试
foreach (Json obj in lsObj)
{
foreach (User user in lsObj.Users)
{
friends.Items.Add(user.UserId);
}
}
答案 1 :(得分:0)
因为有一个数组..您需要一个索引
obj.Users[0].UserId //will get you 68
obj.Users[1].UserId //will get you 69
考虑从更改模型
User[] Users {get; set;}
收件人
List<User> Users {get; set;}
OR
我建议您在第二个循环中使用for循环(如果采用此路线,则不要理会您的模型)
for(int i = 0; i < obj.Users.Count(); i++)
{
friends.Items.Add(obj.Users[i].UserId);
}