我想解析這個JSON對象並將其綁定到Xamarin.Forms中的ListView。Xamarin.Forms JSON對象到列表視圖
我完全失去了如何處理它,因爲我對Xamarin Forms完全陌生。
有沒有更簡單的方法來做到這一點?
我返回的JSON對象
[
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret"
},
{
"id": 2,
"name": "Ervin Howell",
"username": "Antonette"
}
]
這裏是我的代碼來處理餘下的JSON響應
public class RestClient
{
public RestClient()
{
}
public async Task<User[]> GetUsersAsync() {
var client = new System.Net.Http.HttpClient();
client.BaseAddress = new Uri("http://jsonplaceholder.typicode.com");
var response = client.GetAsync("users");
var usersJson = response.Result.Content.ReadAsStringAsync().Result;
var rootobject = JsonConvert.DeserializeObject<Rootobject>(usersJson);
return rootobject.Users;
}
}
Users.cs
public class Rootobject
{
public User[] Users { get; set; }
}
public class User
{
public string id { get; set; }
public string username { get; set; }
}
ListView Form Code
var sv = new RestClient();
var es = sv.GetUsersAsync();
Xamarin.Forms.Device.BeginInvokeOnMainThread (() => {
Debug.WriteLine("Found " + es.Result.Length + " users");
listView.ItemsSource = es.Result;
});
XAML
public ListViewPage()
{
Title = "Users";
var sv = new RestClient();
var es = sv.GetUsersAsync();
Xamarin.Forms.Device.BeginInvokeOnMainThread (() => {
Debug.WriteLine("Found " + es.Result.Length + " users");
listView.ItemsSource = es.Result;
});
listView = new ListView();
listView.ItemTemplate = new DataTemplate(typeof(TextCell));
listView.ItemTemplate.SetBinding(TextCell.TextProperty, "username");
listView.ItemTemplate = new DataTemplate(typeof(ItemCell));
Content = new StackLayout {
Children = {
listView
}
};
}
我應該如何實現一個進度微調(思考微調),以便視圖加載速度快,只顯示微調,直到它已經加載了JSON? – dasmikko 2015-03-04 09:00:25
我編輯了OnAppearing重載,以顯示您將顯示/隱藏微調器的位置。以下是該指標的API:http://iosapi.xamarin.com/?link=T%3aXamarin.Forms.ActivityIndicator – SKall 2015-03-04 14:55:07
感謝您的幫助! – dasmikko 2015-03-04 14:57:30