C#中的JSON对象到Datatable

时间:2016-08-27 05:45:27

标签: c# json datatable

我有以下c#Class

public class Output
        {
            public string name { get; set; }
            public string[] results { get; set; }
        }

执行后导致输出低于

[
  {
    "name": "Field1",
    "results": [
      "One",
      "Two",
      "Three"
    ]
  },
  {
    "name": "Field2",
    "results": [
      "One",
      "Two",
      "Three",
      "Four"
    ]
  }
]

是否有可以将我的JSON转换为DataTable的实用程序或库。我检查了here is the screenshot of the form但是要求JSON必须采用以下格式才能将其转换为表格

string json = @"[{"Field1" : "One", "Field2": "One"}
{"Field1" : "Two", "Field2": "Two"}
{"Field1" : "Three", "Field2": "Three"}
{"Field1" : "", "Field2": "Four"}];

var table = JsonConvert.DeserializeObject<DataTable>(json);

此外,任何线索,如果我的JSON可以转换为JsonConvert.DeserializeObject的格式需要

它没有重复,重复标记的问题讨论了最好的方法,而不是我在这里提供的复杂JSON格式示例。

预期输出

Field1,  Field2
One, One
Two, Two
Three, Three
null,Four

5 个答案:

答案 0 :(得分:2)

JsonConver.DeserializeObject并未为您提供实现目标的简便方法。从Output列表到DataTable编写一个简单的解析器要容易得多。我为你提供了代码:

public static class Helper
{
    public static DataTable ToDataTable(this List<Program.Output> list)
    {
        var dt = new DataTable();

        // insert enough amount of rows
        var numRows = list.Select(x => x.results.Length).Max();
        for (int i = 0; i < numRows; i++)
            dt.Rows.Add(dt.NewRow());

        // process the data
        foreach (var field in list)
        {
            dt.Columns.Add(field.name);
            for (int i = 0; i < numRows; i++)
                // replacing missing values with empty strings
                dt.Rows[i][field.name] = i < field.results.Length ? field.results[i] : string.Empty; 
        }

        return dt;
    }
}

使用示例:

public class Program
{
    static void Main(string[] args)
    {
        var s = "[{\"name\": \"Field1\", \"results\": [\"One\", \"Two\", \"Three\"]}, {\"name\": \"Field2\", \"results\": [\"One\", \"Two\", \"Three\", \"Four\"]}]";
        var o = JsonConvert.DeserializeObject<List<Output>>(s);
        // convert the list to a DataTable
        var dt = o.ToDataTable();
    }

    public class Output
    {
        public string name { get; set; }
        public string[] results { get; set; }
    }
}

答案 1 :(得分:0)

您可以做的是将JSON数据转换回对象列表,如

JsonConvert.DeserializeObject<List<CustomerJson>>(json);

然后使用转换器方法将其转换为DataTable

public static DataTable ToDataTable<T>(this IList<T> data)
{
    PropertyDescriptorCollection props =
        TypeDescriptor.GetProperties(typeof(T));
    DataTable table = new DataTable();
    for(int i = 0 ; i < props.Count ; i++)
    {
        PropertyDescriptor prop = props[i];
        table.Columns.Add(prop.Name, prop.PropertyType);
    }
    object[] values = new object[props.Count];
    foreach (T item in data)
    {
        for (int i = 0; i < values.Length; i++)
        {
            values[i] = props[i].GetValue(item);
        }
        table.Rows.Add(values);
    }
    return table;        
}

答案 2 :(得分:0)

我建议将JSON转换回Output对象数组。您可以使用JsonDataContractSerializer(需要注释)或JavascriptSerializer(需要引用System.Web.Extensions)来实现此目的。

拥有一组Output对象,您可以执行以下操作:

DataTable ConstructDataTable(Output[] outputArray)
{
  var table = new DataTable();
  var columnNames = outputArray.Select(i => i.name).Distinct().ToArray();
  var rows = outputArray.SelectMany(i => i.result).Distinct().ToArray();
  foreach(var cn in columnNames)
     table.Columns.Add(cn, typeof(string));
  foreach(var r in rows)
  {
    object[] values = new object[columnNames.Length];
    for (int i = 0; i < columnNames.Length; i++)
    {
      values[i] = outputArray.First(i => i.name == columnNames[i]).results.FirstOrDefault(i => i == r);
    }
    table.Rows.Add(values);
  }
  return table;
}

答案 3 :(得分:0)

使用了Referances:

  using Newtonsoft.Json;
  using System.Collections.Generic;
  using System.Data;
  using System.IO;
  using FastMember;

你的班级:

  public class Output
  {
        public string name { get; set; }
        public string[] results { get; set; }
  }

并且:

        var s = "[{\"name\": \"Field1\", \"results\": [\"One\", \"Two\", \"Three\"]}, {\"name\": \"Field2\", \"results\": [\"One\", \"Two\", \"Three\", \"Four\"]}]";
        List<Output> data = JsonConvert.DeserializeObject<List<Output>>(s);

        DataTable dt = new DataTable(); 
        using (var reader = ObjectReader.Create(data))
        {
            dt.Load(reader);
        }

答案 4 :(得分:0)

DataTable dt = (DataTable)JsonConvert.DeserializeObject(json, (typeof(DataTable)));