(Json.NET) JsonConvert.DeserializeObject<DataTable>()
works with a populated array but, not with an empty array ( [],
as seen in my example: jsonString2 → col2 ). I would like it to create a string[] column by default, or skip, or otherwise avoid the exception.
Screenshot:
Code (Update 1: Removed extra comma after col3 and still getting exception.):
[TestMethod]
public void TestSerializeEmptyArray()
{
var jsonString1 = @"[
{
""col1"": ""bd3013bb-39a3-4704-b7c9-803c220f8abe"",
""col2"": [
""57ae6e0e-0c20-4da5-a246-b949c71ef551"",
""2bafe349-4b29-4161-814a-5a369459b78c""
],
""col3"": ""b2c172ea-e48c-4e20-9bee-3470278bd801""
}]";
var test1 = JsonConvert.DeserializeObject<DataTable>(jsonString1);
var jsonString2 = @"[
{
""col1"": ""bd3013bb-39a3-4704-b7c9-803c220f8abe"",
""col2"": [],
""col3"": ""b2c172ea-e48c-4e20-9bee-3470278bd801""
}]";
var test2 = JsonConvert.DeserializeObject<DataTable>(jsonString2);
}
Exception:
Newtonsoft.Json.JsonSerializationException HResult=0x80131500 Message=Unexpected JSON token when reading DataTable: EndArray. Path '[0].col2', line 4, position 12. Source=Newtonsoft.Json StackTrace: at Newtonsoft.Json.Converters.DataTableConverter.GetColumnDataType(JsonReader reader) at Newtonsoft.Json.Converters.DataTableConverter.GetColumnDataType(JsonReader reader) at Newtonsoft.Json.Converters.DataTableConverter.CreateRow(JsonReader reader, DataTable dt, JsonSerializer serializer) at Newtonsoft.Json.Converters.DataTableConverter.ReadJson(JsonReader reader, Type objectType, Object existingValue, JsonSerializer serializer) at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.DeserializeConvertable(JsonConverter converter, JsonReader reader, Type objectType, Object existingValue) at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent) at Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType) at Newtonsoft.Json.JsonConvert.DeserializeObject(String value, Type type, JsonSerializerSettings settings) at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value, JsonSerializerSettings settings) at Newtonsoft.Json.JsonConvert.DeserializeObject[T](String value)
Update 1: @D-Shih I removed the extra comma after col3 to make that "Json Parser" happy but, I still get the same exact Exception. Note that I do not get any error on test1
but I do get the error on test2
.