I am trying to deserialize json string to datable and I am getting format error.
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)rn at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.DeserializeConvertable(JsonConverter converter, JsonReader reader, Type objectType, Object existingValue)rn at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)rn at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType)
Please let me know what is the error with json string.
2
Answers
Your JSON string is structured as an object with properties
Arg1, Arg2,
andDataArray
, whereDataArray
is an array of objects. the JSON needs to be deserialize as a class first them loop theList
to createDataTable
Your json string is a json object, but contains a nested json array. Only json array can be converted directly to DataTable:
or you can create a class (especially if you need all data)