如何格式化JSON值并在datagridview

时间:2018-04-19 18:48:33

标签: c# json datagridview json-deserialization

在我的asp.net Web API中,JSON字符串返回如下。

[
  {
    "Company": "Company A",
    "ProjectName": "Project A",
    "Developer": "No developer assigned",
    "Hour": 0,
    "Overtime": 0,
    "Contribution": "0"
  },
  {
    "Company": "Company A",
    "ProjectName": "Project B",
    "Developer": "paul",
    "Hour": 36,
    "Overtime": 27,
    "Contribution": "71.5909%"
  },
  {
    "Company": "Company A",
    "ProjectName": "Project B",
    "Developer": "kalpa",
    "Hour": 16,
    "Overtime": 9,
    "Contribution": "28.4091%"
  },
  {
    "Company": "Company B",
    "ProjectName": "Project C",
    "Developer": "shane",
    "Hour": 40,
    "Overtime": 14,
    "Contribution": "78.2609%"
  },
  {
    "Company": "Company B",
    "ProjectName": "Project C",
    "Developer": "kal",
    "Hour": 10,
    "Overtime": 5,
    "Contribution": "21.7391%"
  },
  {
    "Company": "Company C",
    "ProjectName": "Project D",
    "Developer": "No developer assigned",
    "Hour": 0,
    "Overtime": 0,
    "Contribution": "0"
  },
  {
    "Company": "Company D",
    "ProjectName": "Project E",
    "Developer": "No developer assigned",
    "Hour": 0,
    "Overtime": 0,
    "Contribution": "0"
  }
]

当我在我的C#桌面应用程序上使用我的API并将该JSON字符串显示为以下图像时:

enter image description here

这是我的C#桌面应用程序代码,用于在datagridview方法中显示setGrid中的JSON对象,该方法将JSON对象作为参数显示在datgridview上。

public void setGrid(string obj)
{
    try
    {
        var json = JsonConvert.DeserializeObject<dynamic>(obj);
        dataGridView1.DataSource = json;
    }
    catch (Exception)
    {
        throw;
    }
}

但我需要将此结果显示为以下图像。我需要将公司列合并为相同的值。此图像显示预期结果:

enter image description here

我该怎么做?

1 个答案:

答案 0 :(得分:0)

因此,在看到图像之后,任务似乎需要System.Linq。您首先需要对数据进行分组。

我创建了一个方法,为我提供了你提到的JSON

public static IEnumerable<ProjectInfo> GetResponse()
{
        IEnumerable<ProjectInfo> items = new List<ProjectInfo>();
        using (StreamReader r = new StreamReader("Data.json"))
        {
            string json = r.ReadToEnd();
            items = JsonConvert.DeserializeObject<List<ProjectInfo>>(json);
        }
        return items;
}

ProjectInfo类的定义如下:

public class ProjectInfo
{
    public string Company { get; set; }
    public string ProjectName { get; set; }
    public string Developer { get; set; }
    public int Hour { get; set; }
    public int Overtime { get; set; }
    public string Contribution { get; set; }
}

现在转到代码,使用System.Linqlist属性<{1}}进行分组

Company

现在你有一个分组的集合。使用以下模板作为var APIResponse = GetResponse(); var grouped = APIResponse.GroupBy(x => x.Company);

GridView

来源:

Link 1 Link 2 Link 3