doujingke4981 2019-02-05 18:57
浏览 424
已采纳

如何使用JSON填充ObservableCollection?

How to fill ObservableCollection using JSON? Now there is only the script itself and the model in the desktop application. I can not understand how to tie it up. I get it after running the script:

{
"records": [
    {
        "brand_id": "1",
        "brand_name": "Gigabyte"
    },
    {
        "brand_id": "2",
        "brand_name": "MSI"
    },
    {
        "brand_id": "3",
        "brand_name": "Lenovo"
    },
    {
        "brand_id": "4",
        "brand_name": "Dell"
    },
    {
        "brand_id": "5",
        "brand_name": "Google"
    }
]}

And I have a Model in app:

public class Brands
{
    int brand_id;
    string brand_name;

    public int Brand_id { get => brand_id; set => brand_id = value; }
    public string Brand_name { get => brand_name; set => brand_name = value; }
}

And Collection:

public class BrandsCollection
{
    private ObservableCollection<Brands> brands;

    public ObservableCollection<Brands> Brands { get => brands; set => brands = value; }
}
  • 写回答

1条回答 默认 最新

  • dqly83915 2019-02-05 19:36
    关注

    It is fairly straight forward, especially with packages available to simplify a lot of the work. The Nuget Package System.Net.Http will have the packages you need to create an HttpClient to Get() your JSON from the web. I recommend Newtonsoft.Json to parse JSON into a C# object. And then having the object you just need to set the DataGrid.ItemSource to be an array of objects of any type for it to generate columns.

    A simple example:

    First you would define a simple object representation of your JSON data. For instance if you had the following data:

    [
      {
        "Name":"Test",
        "Data": ["Item1","Item2"]
      },
      {
        "Name":"Test 2",
        "Data": ["Item3","Item4"]
      }
    ]
    

    You would have to create an equivalent C# representation. Basically this is a List of objects so:

    public class OuterObject : List<InnerObject> {}
    

    The inner object is as follows:

    public class InnerObject {
      public string Name { get; set; }
      public List<string> Data { get; set; }
    }
    

    Having the objects defined you can do something like:

    HttpClient client = new HttpClient { BaseAddress = new Uri("ADDRESS") };
    var json = await client.GetAsync("/ENDPOINT");
    JsonSerializer serializer = JsonSerializer.CreateDefault();
    
    using (StringReader reader = new StringReader(json))
    {
         using (JsonTextReader jsonReader = new JsonTextReader(reader))
         {
              var result = serializer.Deserialize<OuterObject>(jsonReader);
         }
    }
    

    Then to access the data in your program you can access it like so:

    string name = result[0].Name;
    

    Or set it to a DataGrid's ItemSource to have the Data show up magically.

    grid1.ItemSource = result;
    

    As long as the result is an array of items it will create a row per item. You may want to specify which items are shown but that is done by modifying DataGrid.Columns definitions and setting DataGrid.AutogenerateColumns = false

    EDIT: With your data and models

    //Just a small change to the Collection
    public class BrandsCollection {
        private ObservableCollection<Brands> _records;
    
        public ObservableCollection<Brands> records { get => _records; set => _records= value; }
    }
    

    And to parse the data...

    JsonSerializer serializer = JsonSerializer.CreateDefault();
    
    using (StringReader reader = new StringReader(json))
    {
         using (JsonTextReader jsonReader = new JsonTextReader(reader))
         {
              var result = serializer.Deserialize<BrandsCollection>(jsonReader);
         }
    }
    

    You have to remember to either use the same names as the json labels or use Json Attributes. For more info on that you can go to the official Newtonsoft.Json documentation

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘