【问题标题】:Consuming RESTful API with Xamarin.forms使用 Xamarin.forms 使用 RESTful API
【发布时间】:2019-03-19 21:20:40
【问题描述】:

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();
}

}

MainPage.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;

    }
}
}

MainPage.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>

【问题讨论】:

  • 对于 web api 和 xamrin forms 应用程序之间的故障排除问题,首先使 web api 工作。您可以使用 Postman (getpostman.com) 等工具测试您的 Web api。在这个阶段不需要使用 xamarin 表单应用程序。 Web api 正常工作后,您可以在 Visual Studio 中调试您的移动应用程序并查看问题所在。
  • GetGames 返回单个字符串值,但 ListView ItemsSource 必须是 IEnumerable(即数组/列表/集合)。我猜 GetGames 返回一个 json 数组,如果是这样,您需要告诉 Refit 将其反序列化为正确的类型

标签: c# rest api xamarin.forms


【解决方案1】:

根据this documentationGetOwnedGames 将返回一个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.
}

(参见JsonProperty 上的JSON.Net documentation

您现在可以重新定义您的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;

【讨论】:

    猜你喜欢
    • 2012-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多