【问题标题】:How to display JSON data in Xamarin.forms list view?如何在 Xamarin.forms 列表视图中显示 JSON 数据?
【发布时间】:2017-11-30 09:47:07
【问题描述】:

我是xamarin.forms 的新手,我想构建一个跨平台应用程序,它将在列表视图中显示 JSON 数据。这是我的 JSON 数据。

{
  "fish_product": [
    {
      "fish_id": "1",
      "fish_img": "",
      "fish_name": "Indian Mackerel",
      "fish_category": "Marine Fish",
      "size": "Medium",
      "price": "100"
    },
    {
      "fish_id": "2",
      "fish_img": "",
      "fish_name": "Manthal Repti",
      "fish_category": "Marine Fish",
      "size": "Small",
      "price": "200"
    },
    {
      "fish_id": "4",
      "fish_img": "",
      "fish_name": "Baby Sole Fish",
      "fish_category": "Marine Fish",
      "size": "Small",
      "price": "600"
    }
 ]
}

我想在列表视图中显示“fish_name”。请为此提出任何解决方案或任何文章或教程。提前谢谢你。

【问题讨论】:

标签: json xamarin.forms cross-platform hybrid-mobile-app


【解决方案1】:

我认为您必须将此 JSON 反序列化为类似

的对象
public class FishProduct
{
    public string fish_id { get; set; }
    public string fish_img { get; set; }
    public string fish_name { get; set; }
    public string fish_category { get; set; }
    public string size { get; set; }
    public string price { get; set; }
}

public class RootObject
{
    public ObservableCollection<FishProduct> fish_product { get; set; }
}

然后你必须使用 ListView 来设置你的listview.ItemsSource = myList.fish_product

然后你必须使用ViewCell创建一个DataTemplate

在这个 ViewCell 中,您可以在 SetBinding fish_name 字段时拥有一个 Label。在类似的代码中

Label label = new Label();
label.SetBinding(Label.TextProperty, "fish_name");

我想你可以看看ListView Documents

【讨论】:

  • 先生,您能推荐异步调用示例吗?@Alessandro Caliaro
  • 异步调用是为了什么?你的问题是“如何显示......”你不需要异步。你需要绑定
【解决方案2】:

我觉得这对你有帮助

你的模型

public class FishProduct
{
    public string fish_id { get; set; }
    public string fish_img { get; set; }
    public string fish_name { get; set; }
    public string fish_category { get; set; }
    public string size { get; set; }
    public string price { get; set; }
}

public class RootObject
{
    public List<FishProduct> fish_product { get; set; }
}

Web 服务调用和 JSON 反序列化

public async Task GetData()
{
 try
  {
  HttpClient client = new HttpClient();
  var result = await client.GetAsync("http://yourJSON_Url");
  result.EnsureSuccessStatusCode();
  string json = await result.Content.ReadAsStringAsync();
  List<FishProduct>  res= JsonConvert.DeserializeObject<List<FishProduct>>(json);

  }
 catch (Exception ex)
 {
   throw;
  }
}

【讨论】:

    猜你喜欢
    • 2020-01-06
    • 1970-01-01
    • 1970-01-01
    • 2017-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-23
    相关资源
    最近更新 更多