如何使用JSON填充ObservableCollection?

时间:2019-02-05 18:57:15

标签: c# php json observablecollection wpfdatagrid

如何使用JSON填充ObservableCollection?现在,桌面应用程序中只有脚本本身和模型。我不明白该怎么绑。 我在运行脚本后得到它:

{
"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"
    }
]}

我在应用程序中有一个模型:

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

收藏:

public class BrandsCollection
{
    private ObservableCollection<Brands> brands;

    public ObservableCollection<Brands> Brands { get => brands; set => brands = value; }
}

1 个答案:

答案 0 :(得分:0)

这相当简单,尤其是使用可简化许多工作的软件包。 Nuget软件包System.Net.Http将包含您需要创建一个HttpClientGet()网络上的JSON的软件包。我建议使用Newtonsoft.Json将JSON解析为C#对象。然后有了对象,您只需要将DataGrid.ItemSource设置为任何类型的对象数组即可生成列。

一个简单的例子:

首先,您将定义JSON数据的简单对象表示形式。 例如,如果您有以下数据:

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

您将必须创建等效的C#表示形式。 基本上,这是一个对象列表,所以:

public class OuterObject : List<InnerObject> {}

内部对象如下:

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

定义了对象之后,您可以执行以下操作:

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

然后访问程序中的数据,您可以像这样访问它:

string name = result[0].Name;

或将其设置为DataGrid's ItemSource,以神奇地显示数据。

grid1.ItemSource = result;

只要结果是一个项目数组,它将为每个项目创建一行。 您可能要指定显示哪些项目,但可以通过修改DataGrid.Columns定义并设置DataGrid.AutogenerateColumns = false

来完成。

编辑:使用您的数据和模型

//Just a small change to the Collection
public class BrandsCollection {
    private ObservableCollection<Brands> _records;

    public ObservableCollection<Brands> records { get => _records; set => _records= value; }
}

然后解析数据...

JsonSerializer serializer = JsonSerializer.CreateDefault();

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

您必须记住要使用与json标签相同的名称或使用Json Attributes。有关更多信息,请访问官方的Newtonsoft.Json documentation

相关问题