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 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!