JSON对象到C#中的数据表 [英] JSON object to Datatable in C#
问题描述
我有以下c#类
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的实用程序或库.我检查了 JSON.net示例,但要求JSON必须在下面将其转换为表格的格式
Is there any utility or library which can convert my JSON into DataTable. I checked the JSON.net example but that require the JSON must be in below format to convert that into table
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的格式进行转换的任何线索
Also, Any clue if my JSON can be converted in the format needs for JsonConvert.DeserializeObject
这不是重复项,重复项中标记的问题讨论的是最佳方法,而不是我在此处提供的复杂JSON格式示例.
It's not duplicate, the question marked in duplicate discusses the best way instead the complex JSON format example i provided here.
预期产量
Field1, Field2
One, One
Two, Two
Three, Three
null,Four
推荐答案
JsonConver.DeserializeObject
不能为您提供实现目标的简便方法.从Output
列表到DataTable
编写一个简单的解析器会容易得多.我为您提供代码:
JsonConver.DeserializeObject
does not provide you with an easy way to achieve your goal. It would be much easier to write a simple parser from a list of Output
s to a DataTable
. I provide you with code:
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; }
}
}
这篇关于JSON对象到C#中的数据表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!