【发布时间】:2019-08-10 10:42:31
【问题描述】:
我正在尝试从 json 下载日期并将其放在列表视图中,但我不知道该怎么做。 我使用邮递员从我的 YRL 下载这些信息:
{"users":[{"email":"ciccio@libero.it","nickname":"Franco","image":"http://localhost/MyWebService/images/"},{"电子邮件":"email@test.it","昵称":"昵称","图片":"http://localhost/MyWebService/images/test_img.png"},{"email":"provoo@controllo.它","昵称":"farfallo","image":"http://localhost/MyWebService/images/"}]}
现在要将这些信息下载到我的应用程序中,我创建了这些类:
public class Users
{
[JsonProperty("users", NullValueHandling = NullValueHandling.Ignore)]
public User[] UsersUsers { get; set; }
}
public class User
{
[JsonProperty("email", NullValueHandling = NullValueHandling.Ignore)]
public string email { get; set; }
[JsonProperty("nickname", NullValueHandling = NullValueHandling.Ignore)]
public string nickname { get; set; }
[JsonProperty("password", NullValueHandling = NullValueHandling.Ignore)]
public string password { get; set; }
[JsonProperty("image", NullValueHandling = NullValueHandling.Ignore)]
public Uri image { get; set; }
}
在我的 XAML 页面上,我编写了以下代码:
<?xml version="1.0" encoding="UTF-8" ?>
<ContentPage
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="TestLoginURL.View.HomePage">
<ContentPage.Content>
<StackLayout>
<Label Text="HomePage"></Label>
<ListView x:Name="ListViewUsers" RowHeight="60">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Orientation="Vertical" Padding="8,0,8,0">
<Image Source="{Binding image}" />
<Label Text="{Binding nickname}" />
<Label Text="{Binding email}" />
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ContentPage.Content>
</ContentPage>
在 .cs 文件中我写了这些东西:
public partial class HomePage : ContentPage
{
public HomePage(Model.Users users)
{
InitializeComponent();
LoadData();
}
public async void LoadData()
{
HttpClient client = new HttpClient();
var url = "http://192.168.178.77/TestLoginURL/api/getAllUsers.php";
client.BaseAddress = new Uri(url);
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync(url);
var content = await response.Content.ReadAsStringAsync();
var usersList = JsonConvert.DeserializeObject<List<Users>>(content);
ListViewUsers.ItemsSource = usersList;
}
}
但不幸的是,当我打开此页面时,出现此错误并且应用程序陷入崩溃:
Newtonsoft.Json.JsonSerializationException
无法将当前 JSON 对象(例如 {"name":"value"})反序列化为类型 'System.Collections.Generic.List`1[TestLoginURL.Model.Users]' 因为该类型需要 JSON 数组(例如[1,2,3]) 正确反序列化。 要修复此错误,要么将 JSON 更改为 JSON 数组(例如 [1,2,3]),要么将反序列化类型更改为普通的 .NET 类型(例如,不是像整数这样的原始类型,而不是像这样的集合类型可以从 JSON 对象反序列化的数组或列表。 JsonObjectAttribute 也可以添加到类型中以强制它从 JSON 对象反序列化。 路径“用户”,第 1 行,位置 9。
那么...谁能告诉我在 JSON 的反序列化中我错在哪里以及正确的代码是什么? 谢谢
【问题讨论】:
标签: c# json xaml listview xamarin