我在這裏回顧了答案:轉換數據表到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