C# Xamarin.Froms错误:Models.User无法转换为类型';System.Collections.IEnumerable';
我正在使用Xamarin和MVVM模型构建一个跨平台应用程序。我已经对我当前的问题做了很多研究,但没有在论坛上找到对我有帮助的答案/线索。所以,我决定分享它,并希望得到帮助。我有一个后端服务器,在那里我可以通过访问令牌进行API调用。在我的后端,我创建了一个帐户表,其中有firstname、lastname、email等行。我在移动应用程序中创建了一个用户视图模型,可以在其中显示经过验证的用户信息。当我调试时,我可以看到我成功地获取了用户信息,但是,我无法将结果绑定到我的视图中,获取以下错误:Models.user无法转换为“System.Collections.IEnumerable”类型。我想不出是什么。任何帮助都将不胜感激 这是我的API服务代码,我在其中对后端服务器进行API调用,并使用访问令牌获取用户信息:C# Xamarin.Froms错误:Models.User无法转换为类型';System.Collections.IEnumerable';,c#,xamarin.forms,C#,Xamarin.forms,我正在使用Xamarin和MVVM模型构建一个跨平台应用程序。我已经对我当前的问题做了很多研究,但没有在论坛上找到对我有帮助的答案/线索。所以,我决定分享它,并希望得到帮助。我有一个后端服务器,在那里我可以通过访问令牌进行API调用。在我的后端,我创建了一个帐户表,其中有firstname、lastname、email等行。我在移动应用程序中创建了一个用户视图模型,可以在其中显示经过验证的用户信息。当我调试时,我可以看到我成功地获取了用户信息,但是,我无法将结果绑定到我的视图中,获取以下错误:M
public async Task<User> GetUsersAsync(string accessToken)
{
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Bearer", accessToken);
var json = await client.GetStringAsync(Constants.BaseApiAddress + "api/Account/UserInfo");
var user = JsonConvert.DeserializeObject<User>(json);
return user;
}
这是我的用户模型
public class User
{
[JsonProperty("FirstName")]
public string FirstName { get; set; }
[JsonProperty("LastName")]
public string LastName { get; set; }
[JsonProperty("Children")]
public string Children { get; set; }
[JsonProperty("Email")]
public string Email { get; set; }
[JsonProperty("Image")]
public string Image { get; set; }
}
这是我的UserProfile视图XAML
<ContentPage.BindingContext>
<viewModels:UserViewModel />
</ContentPage.BindingContext>
<StackLayout Padding="20">
<ListView ItemsSource="{Binding Users}"
HasUnevenRows="True">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Padding="0,10">
<Label Style="{StaticResource ProfileNameLabel}" Text="{Binding Email}" />
<Label Margin="0,-5" Style="{StaticResource ProfileTagLabel}" Text="{Binding FirstName}" />
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
ListView用于显示多个项目的列表,其ItemSource必须是
IEnumerable
(即对象的集合)。您的用户对象只是一个项目。您可以使用户
成为一个列表
,其中只包含一个项目
public List<User> Users
公开用户列表
或者您可以使用不同的UI元素来显示数据只要添加一个
observateCollection
,如果您假装添加和删除用户,它将使您的生活更简单。将其作为列表检索会导致以下错误:Newtonsoft.Json.Json序列化异常:无法反序列化当前Json对象(例如{“name”):“value”})转换为类型“System.Collections.ObjectModel.ObservableCollection`1[App.Models.User]”,因为该类型需要JSON数组(例如[1,2,3])要正确反序列化。您的数据不是列表/数组!这就是问题所在。您需要创建一个列表并将单个数据项插入其中。这不需要对反序列化进行任何更改。哦,现在这很有意义。谢谢Jason!
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class UserProfilePage : ContentPage
{
UserViewModel usersViewModel;
public UserProfilePage ()
{
InitializeComponent ();
BindingContext = usersViewModel = new UserViewModel();
}
protected override void OnAppearing()
{
base.OnAppearing();
usersViewModel.GetUserCommand.Execute(null);
}
}
public List<User> Users