我有一个这样的代码,
DataTable dt = new DataTable();
string data = "{"ProductId":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77],"ProductName":["Chai","Chang","Aniseed Syrup","Chef Anton's Cajun Seasoning","Chef Anton's Gumbo Mix","Grandma's Boysenberry Spread","Uncle Bob's Organic Dried Pears","Northwoods Cranberry Sauce","Mishi Kobe Niku","Ikura","Queso Cabrales","Queso Manchego La Pastora","Konbu","Tofu","Genen Shouyu","Pavlova","Alice Mutton","Carnarvon Tigers","Teatime Chocolate Biscuits","Sir Rodney's Marmalade","Sir Rodney's Scones","Gustaf's Knäckebröd","Tunnbröd","Guaraná Fantástica","NuNuCa Nuß-Nougat-Creme","Gumbär Gummibärchen","Schoggi Schokolade","Rössle Sauerkraut","Thüringer Rostbratwurst","Nord-Ost Matjeshering","Gorgonzola Telino","Mascarpone Fabioli","Geitost","Sasquatch Ale","Steeleye Stout","Inlagd Sill","Gravad lax","Côte de Blaye","Chartreuse verte","Boston Crab Meat","Jack's New England Clam Chowder","Singaporean Hokkien Fried Mee","Ipoh Coffee","Gula Malacca","Rogede sild","Spegesild","Zaanse koeken","Chocolade","Maxilaku","Valkoinen suklaa","Manjimup Dried Apples","Filo Mix","Perth Pasties","Tourtière","Pâté chinois","Gnocchi di nonna Alice","Ravioli Angelo","Escargots de Bourgogne","Raclette Courdavault","Camembert Pierrot","Sirop d'érable","Tarte au sucre","Vegie-spread","Wimmers gute Semmelknödel","Louisiana Fiery Hot Pepper Sauce","Louisiana Hot Spiced Okra","Laughing Lumberjack Lager","Scottish Longbreads","Gudbrandsdalsost","Outback Lager","Flotemysost","Mozzarella di Giovanni","Röd Kaviar","Longlife Tofu","Rhönbräu Klosterbier","Lakkalikööri","Original Frankfurter grüne Soße"]}";
dt = JsonConvert.DeserializeObject<DataTable>(data);
如果我在在线json编辑器上以removechar的形式运行这些数据,它就会显示出来。但在Visual Studio中,出现了一个错误,
Unexpected JSON token when reading DataTable. Expected StartArray, got StartObject. Path '', line 1, position 1.
在最后一个代码位置。
我想,使用Newtonsoft插件将数据转换为DataTable。我该如何解决这个问题?谢谢
json必须是要转换为DataTable的对象数组,它必须像这样开始:
"[{"ProductId..........
末端是这样的:
....,"fieldName":Value}]"
您的data
无法转换为Datatabe
当我尝试你的代码时,它会给我:
完成反序列化后在JSON字符串中发现其他文本对象
然而,当我这样做时:
object obj = JsonConvert.DeserializeObject(data);
工作良好。
你也可以创建自己的类:
public class MyObject
{
public int[] productId { get; set; }
public string[] ProductName { get; set; }
}
MyObject obj = JsonConvert.DeserializeObject<MyObject>(data);
因此,对于您拥有的不同类型的数据,您可以创建不同的类:
public class MyObject2{
...
}
public class MyObject3{
...
}
...
Object obj = null;
try{
obj = JsonConvert.DeserializeObject<MyObject>(data);
}catch{
try{
obj = JsonConvert.DeserializeObject<MyObject2>(data);
}catch{
try{
obj = JsonConvert.DeserializeObject<MyObject3>(data);
}catch{
//Log error new type of data received
throw new Exception();
}
}
}
if (obj.GetType() == typeof(MyObject)){
...
}else if (obj.GetType() == typeof(MyObject2)){
...
}
....