【问题标题】:Consume Rest service from Xamarin app从 Xamarin 应用程序使用 Rest 服务
【发布时间】:2018-04-24 16:53:53
【问题描述】:

我已经从 xamarin 表单中消费了休息服务。但我的列表视图没有显示出来。它只显示了很多空行。

休息服务响应

[
   {
      "prodName":"abc",
      "qty":142.0,
      "price":110.0
   },
   {
      "prodName":"efg",
      "qty":20.0,
      "price":900.0
   }
]

我的 .xaml 文件

<ListView x:Name="ProductsListView">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <StackLayout Orientation="Horizontal">

                    <Label Text="{Binding prodName}" TextColor="Black"></Label>
                    <Label Text="{Binding price}" TextColor="Black"></Label>
                </StackLayout>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

xaml.cs 文件

private async void GetProducts()
{
    HttpClient client = new HttpClient();

    var response = await client.GetStringAsync("http://myUrl/Api/Values");
    var products = response;
    ProductsListView.ItemsSource = products;
}

【问题讨论】:

    标签: c# xaml xamarin xamarin.forms


    【解决方案1】:

    这不是这样的。您现在正在做的是将 JSON 下载为原始字符串值并将其放入 ListView。

    您必须将下载的字符串反序列化为 .NET 对象。

    这样定义模型:

    public class ApiModel
    {
        [JsonProperty("prodName")]
        public string prodName { get; set; }
    
        [JsonProperty("qty")]
        public long qty { get; set; }
    
        [JsonProperty("price")]
        public long price { get; set; }
    }
    

    得到这样的结果:

    private async void GetProducts()
    {
        HttpClient client = new HttpClient();
    
        var response = await client.GetStringAsync("http://myUrl/Api/Values");
        var products = JsonConvert.DeserializeObject<ApiModel[]>(response);
        ProductsListView.ItemsSource = products;
    }
    

    您的结果 JSON 字符串现在将转换为 ApiModel 数组,ListView 可以从中读取属性。

    如果您还没有这样做,请安装 JSON.NET 并导入正确的用法(可能是 using Newtonsoft.Json; 和/或 using Newtonsoft.Json.Converters;)。

    您可能想阅读这些内容,更多信息请看这里:https://docs.microsoft.com/en-us/xamarin/xamarin-forms/data-cloud/consuming/rest

    【讨论】:

      【解决方案2】:

      问题是您正在获取 json 结果,并试图将其推送到 listView ItemSource。而是先使用json.net 将您的 json 转换为产品

      给定

      public class Product
      {
          public string prodName { get; set; }
          public double qty { get; set; }
          public double price { get; set; }
      }
      

      示例

      private async void GetProducts()
      {
          HttpClient client = new HttpClient();
      
          var response = await client.GetStringAsync("http://myUrl/Api/Values");
          var products = JsonConvert.DeserializeObject<List<Product>>(response);
          ProductsListView.ItemsSource = products;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-06-05
        • 1970-01-01
        • 1970-01-01
        • 2012-07-16
        • 1970-01-01
        • 2014-01-21
        • 2018-08-27
        • 2014-04-30
        相关资源
        最近更新 更多