[英]Xamarin.Forms: Trying to implement Restful API, but the app keeps crashing
[英]Consuming RESTful API with Xamarin.forms
Xamarin.forms 的新手。
下面的代码应该生成一个游戏列表并将其绑定到一个列表视图,但它没有。 我正在使用改装库。 Postman 中的 URL 按预期返回 JSON 列表。 我应该从哪里开始?
ISteamService.CS
using System.Collections.Generic;
using System.Threading.Tasks;
using Refit;
namespace PatchNotes
{
[Headers("Content-Type: application/json")]
public interface ISteamService
{
[Get("/IPlayerService/GetOwnedGames/v1/?key=XXXXC&include_appinfo=1&steamid=XXXX")]
Task<string> GetGames();
}
}
主页.xaml.cs
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Xamarin.Forms;
using Refit;
namespace PatchNotes
{
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
async void OnGetGamesClicked(object sender, System.EventArgs e)
{
var apiResponse = RestService.For<ISteamService>("https://api.steampowered.com");
var games = await apiResponse.GetGames();
GamesList.ItemsSource = games;
}
}
}
主页.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="PatchNotes.MainPage">
<ContentPage.Content>
<StackLayout Padding="40">
<Button Text="Get Games" Clicked="OnGetGamesClicked"
BackgroundColor="Black" TextColor="White"
HorizontalOptions="FillAndExpand"/>
<ListView x:Name="GamesList">
<ListView.ItemTemplate>
<DataTemplate>
<TextCell Text="{Binding Name}" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
</ContentPage.Content>
根据这个文档, GetOwnedGames
将返回一个具有以下结构的 JSON(正如 Jason 猜对的那样)
{
"game_count": <number of games>,
"games": [
{
"appid": "...",
"name": "...",
"playtime_2weeks": ,
"playtime_forever": ,
"img_icon_url": "",
"img_logo_url": "",
"has_community_visible_stats": ""
}, ...]
}
您不能简单地将此字符串分配给ItemsSource
并期望Xamarin.Forms为您找出答案,您必须注意这是如何反序列化的。
您必须编写一个用于反序列化 JSON 字符串的类。 Refit将执行反序列化,但无论如何您都需要一个类来反序列化:
public class GamesList
{
[JsonProperty("game_count")]
public int GameCount { get; set; }
[JsonProperty("games")]
public List<Game> Games { get; set; }
}
public class Game
{
[JsonProperty("appid")]
public string AppId { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("playtime_2weeks")]
public int PlayedMinutesInTheLastTwoWeeks { get; set; }
// And so on. Depending on what you need.
}
(请参阅JSON.Net文档上JsonProperty
)
您现在可以重新定义您的ISteamService
[Headers("Content-Type: application/json")]
public interface ISteamService
{
[Get("/IPlayerService/GetOwnedGames/v1/?key=XXXXC&include_appinfo=1&steamid=XXXX")]
Task<GamesList> GetGames();
}
并从你的OnGetGamesCicked
使用它
var apiResponse = RestService.For<ISteamService>("https://api.steampowered.com");
var gamesList = await apiResponse.GetGames();
GamesList.ItemsSource = gamesList.Games;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.