【问题标题】:Converting Flat file to List which is a property of another class将平面文件转换为列表,这是另一个类的属性
【发布时间】:2017-02-24 14:14:55
【问题描述】:
public class DummyResponse
{
    public int UpdatedRecords { get; set; }
    public string Id { get; set; }
    public bool Isvalid { get; set; }
}

public class Request
{
    public List<DummyResponse> Changes { get; set; }
    public string ReuestedBy { get; set; }

    public Request()
    {
        Changes = new List<DummyResponse>();
    }
}

我有一个平面文件,其中包含用于虚拟响应的制表符分隔数据。 我希望将其序列化为 Request 对象。 实现需求应该是通用的,因为在这种情况下我只需要用户传递 T(请求)并确定要从平面文件中填充的正确子类型。

我有下面的代码将其转换为对象。它只适用于具有字符串类型的属性。

interface ICollectionBuilder
{
    object Build(IList dictionaries);
}

internal class CollectionBuilder<T> : ICollectionBuilder where T : new()
{
    public object Build(IList dictionaries)
    {
        var dictConverter = new DictionaryConerter<T>();
        return dictionaries
            .OfType<IDictionary<string, object>>()
            .Select(dict => dictConverter.ConvertTyped(dict))
            .ToList();
    }
}

interface IDictionaryConverter
{
    object Convert(IDictionary<string, object> dict);
}

internal class DictionaryConerter<T> : IDictionaryConverter where T : new()
{
    public object Convert(IDictionary<string, object> dict)
    {
        return ConvertTyped(dict);
    }

    public T ConvertTyped(IDictionary<string, object> dict)
    {
        T t = new T();
        var properties = t.GetType().GetProperties();

        foreach (KeyValuePair<string, object> curr in dict)
        {
            if (String.IsNullOrEmpty(curr.Key)) continue;
            if (curr.Value == null) continue;

            Type valType = null;
            Type newType = null;
            PropertyInfo currProperty = null;
            foreach (PropertyInfo p in properties)
            {
                if (String.IsNullOrEmpty(p.Name)) continue;

                if (String.Compare(p.Name.ToLower(), curr.Key.ToLower()) == 0)
                {
                    valType = t.GetType().GetProperty(p.Name).PropertyType;
                    newType = Nullable.GetUnderlyingType(valType) ?? valType;
                    currProperty = p;
                    break;
                }
            }
            object newVal = curr.Value;

            var curDict = curr.Value as IDictionary<string, object>;
            var curList = curr.Value as IList;
            if (curDict != null && newType.GetConstructor(Type.EmptyTypes) != null)
            {
                newVal = ((IDictionaryConverter)Activator.CreateInstance(typeof(DictionaryConerter<>).MakeGenericType(newType))).Convert(curDict);
            }
            else if (
                curList != null &&
                curList.OfType<IDictionary<string, object>>().Any() &&
                newType.IsGenericType &&
                newType.GetGenericTypeDefinition() == typeof(List<>) &&
                newType.GetGenericArguments()[0].GetConstructor(Type.EmptyTypes) != null)
            {
                newVal = ((ICollectionBuilder)Activator.CreateInstance(typeof(CollectionBuilder<>).MakeGenericType(newType.GetGenericArguments()[0]))).Build(curList);
            }

            t.GetType().GetProperty(currProperty.Name).SetValue(t, newVal);
        }

        return t;
    }
}

示例用法:

void Main ()
    {
        var dict = new Dictionary<string,object>();
        dict.Add("ReuestedBy",abc);
        var innerDict = new Dictionary<string,object>();
        var list = new LIst<Dictionary<string,object>>();
        innerDict.Add("UpdatedRecords","45");
        innerDict.Add("Id","1");
        innerDict.Add("IsValid","False");
        dict.Add("Changes",list )
    }

这里的问题是它不适用于字符串以外的任何其他类型。

【问题讨论】:

    标签: c# file reflection deserialization flat


    【解决方案1】:

    我在设置值时使用下面的代码修复了它

                    propertyVal = Convert.ChangeType(propertyVal, targetType);
                    propertyInfo.SetValue(inputObject, propertyVal, null);
    

    【讨论】:

      猜你喜欢
      • 2018-02-21
      • 1970-01-01
      • 2013-07-10
      • 2014-03-06
      • 2021-10-11
      • 2023-03-17
      • 1970-01-01
      • 2011-04-10
      • 1970-01-01
      相关资源
      最近更新 更多