Ejemplo n.º 1
0
        private static void CreateRow(JsonReader reader, DataTable dt, JsonSerializer serializer)
        {
            DataRow row = dt.NewRow();

            reader.ReadAndAssert();
            while (reader.TokenType == JsonToken.PropertyName)
            {
                string columnName = (string)reader.Value;
                reader.ReadAndAssert();
                DataColumn column = dt.Columns[columnName];
                if (column == null)
                {
                    Type columnDataType = DataTableConverter.GetColumnDataType(reader);
                    column = new DataColumn(columnName, columnDataType);
                    dt.Columns.Add(column);
                }

                if (column.DataType == typeof(DataTable))
                {
                    if (reader.TokenType == JsonToken.StartArray)
                    {
                        reader.ReadAndAssert();
                    }
                    DataTable dt1 = new DataTable();
                    while (reader.TokenType != JsonToken.EndArray)
                    {
                        DataTableConverter.CreateRow(reader, dt1, serializer);
                        reader.ReadAndAssert();
                    }

                    row[columnName] = (object)dt1;
                }
                else if (column.DataType.IsArray && column.DataType != typeof(byte[]))
                {
                    if (reader.TokenType == JsonToken.StartArray)
                    {
                        reader.ReadAndAssert();
                    }
                    List <object> objectList = new List <object>();
                    while (reader.TokenType != JsonToken.EndArray)
                    {
                        objectList.Add(reader.Value);
                        reader.ReadAndAssert();
                    }

                    Array instance = Array.CreateInstance(column.DataType.GetElementType(), objectList.Count);
                    ((ICollection)objectList).CopyTo(instance, 0);
                    row[columnName] = (object)instance;
                }
                else
                {
                    object obj = reader.Value != null
            ? serializer.Deserialize(reader, column.DataType) ?? (object)DBNull.Value
            : (object)DBNull.Value;

                    row[columnName] = obj;
                }

                reader.ReadAndAssert();
            }

            row.EndEdit();
            dt.Rows.Add(row);
        }