-1

When I deserialize a json dynamically i get an array with fewer columns on some rows.

using (StreamReader file = File.OpenText(filePath))
{
    dynamic words = JsonConvert.DeserializeAnonymousType(file.ReadToEnd(), new ExpandoObject());
    DataTable dt = ToDataTable(words.wordlist.item);

    return dt;
}

public static DataTable ToDataTable(this IEnumerable<dynamic> items)
    {
        var data = items.ToArray();
        if (data.Count() == 0) return null;

        var dt = new DataTable();
        foreach (var key in ((IDictionary<string, object>)data[0]).Keys)
        {
            dt.Columns.Add(key);
        }
        foreach (var d in data)
        {
            dt.Rows.Add(((IDictionary<string, object>)d).Values.ToArray());
        }
        return dt;
    }

I understand why it does this but I can't find any way to fix it.

Ilias Tsakiridis
  • 58
  • 1
  • 2
  • 10

1 Answers1

0

This might work for you.

DataTable dt = (DataTable)JsonConvert.DeserializeObject(json, (typeof(DataTable)));
Neil B
  • 2,096
  • 1
  • 12
  • 23