我在这里回顾了答案:转换数据表到JSON
- How do you convert a DataTable into a generic list?
- Convert DataTable to Generic List in C# 和
- Fastest way to convert datatable to generic list
但他们不帮我的特定用例。我从SQL数据适配器中检索DataTable,并希望将DataTable转换为List(这很容易),然后将List序列化为JSON(使用JSON.net,这很简单)。这个问题是我似乎不得不使用列表。好,很好 - 让我有这样的代码:
DataTable result = GoMagicallyGatherSomeData();
List<DataRow> ret = new List<DataRow>();
if (result != null && result.Rows.Count > 0)
{
foreach (DataRow curr in result.Rows)
{
ret.Add(curr);
}
}
或
DataTable result = GoMagicallyGatherSomeData();
List<DataRow> ret = result.AsEnumerable().ToList();
当我去序列化的列表,它...是不是我所期望。
我想得到的回复是:
[
{
"TestId":1,
"AccountId":1,
"SomeString":"This is an updated test",
"SomeTimestamp":"2016-01-01T00:00:00Z",
"SomeDecimal":5.55
},
{
"TestId":3,
"AccountId":1,
"SomeString":"This is a third test",
"SomeTimestamp":"2016-01-01T00:00:00Z",
"SomeDecimal":5.55
},
{ ... removed for brevity ... }
]
而我居然得到的回复是:
[
{
"RowError":"",
"RowState":2,
"Table":[
{
"TestId":1,
"AccountId":1,
"SomeString":"This is an updated test",
"SomeTimestamp":"2016-01-01T00:00:00Z",
"SomeDecimal":5.55
},
{
"TestId":3,
"AccountId":1,
"SomeString":"This is a second test",
"SomeTimestamp":"2016-01-01T00:00:00Z",
"SomeDecimal":5.55
},
{ ... removed for brevity ... }
],
"ItemArray":[
1,
1,
"This is an updated test",
"2016-01-01T00:00:00Z",
5.55
],
"HasErrors":false
},
{
"RowError":"",
"RowState":2,
"Table":[
... there seems to be an instance of this for every row in the result ...
],
"ItemArray":[
1,
1,
"This is an updated test",
"2016-01-01T00:00:00Z",
5.55
],
"HasErrors":false
}
]
另一个挑战是,我需要做的这一点没有实际的认识数据的类型。
任何见解?任何人都有最好的方法来做这个建议?我能否从第一个序列化的DataRow中拷出'table'数组,或者,后续的序列化的DataRows实际上是否包含与第一个不同的数据?
您需要一个DTO来生成JSON。 – rism
为什么downvote请? – joelc