我正在尝试将 json 字符串反序列化为 datable,但出现格式错误。
string str = "{\"Arg1\":\"Arg1Value\",\"Arg2\":\"Arg2Value\",\"DataArray\":[{\"Id\": \"2222\",\"VehicleNo\": \"234354\",\"Amount\":\"1000\"},{\"Id\":\"2226\",\"VehicleNo\":\"2343\",\"Amount\":\"2000\"}]"}";
DataTable data = Newtonsoft.Json.JsonConvert.DeserializeObject<DataTable>(str);
Error:
Unexpected JSON token when reading DataTable. Expected StartArray, got StartObject. Path '', line 1, position 1.","Data":null,"InnerException":null,"HelpURL":null,"StackTraceString":" at Newtonsoft.Json.Converters.DataTableConverter.ReadJson(JsonReader reader, Type objectType, Object existingValue, JsonSerializer serializer)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.DeserializeConvertable(JsonConverter converter, JsonReader reader, Type objectType, Object existingValue)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)\r\n at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)\
请让我知道 json 字符串有什么错误。
您的 JSON 字符串被构造为具有属性
Arg1, Arg2,
和 DataArray
的对象,其中 DataArray
是对象数组。 JSON 需要先反序列化为类,然后循环 List
来创建 DataTable
string str = "{\"Arg1\":\"Arg1Value\",\"Arg2\":\"Arg2Value\",\"DataArray\":[{\"Id\": \"2222\",\"VehicleNo\": \"234354\",\"Amount\":\"1000\"},{\"Id\":\"2226\",\"VehicleNo\":\"2343\",\"Amount\":\"2000\"}]}";
class DataItem
{
public string Id { get; set; }
public string VehicleNo { get; set; }
public string Amount { get; set; }
}
class MyJsonType
{
public string Arg1 { get; set; }
public string Arg2 { get; set; }
public List<DataItem> DataArray { get; set; }
}
var myObject = JsonConvert.DeserializeObject<MyJsonType>(str);
DataTable dataTable = new DataTable();
dataTable.Columns.Add("Id", typeof(string));
dataTable.Columns.Add("VehicleNo", typeof(string));
dataTable.Columns.Add("Amount", typeof(string));
foreach (var item in myObject.DataArray)
{
dataTable.Rows.Add(item.Id, item.VehicleNo, item. Amount);
}