如何在Xamarin.forms列表视图中显示JSON数据?

时间:2017-06-27 10:58:38

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

我是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”。请为此建议任何解决方案或任何文章或教程。提前谢谢你。

2 个答案:

答案 0 :(得分:0)

我认为你必须将这个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

答案 1 :(得分:0)

我认为这可能会对你有所帮助

你的模特

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

Webservice调用和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;
  }
}