WCF: Serializing and Deserializing generic collections

后端 未结 4 1311
青春惊慌失措
青春惊慌失措 2020-12-10 01:25

I have a class Team that holds a generic list:

[DataContract(Name = \"TeamDTO\", IsReference = true)]
public class Team
{
    [DataMember]
    private IList&         


        
4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-10 02:16

    Taken straight from my blog. i hope it will be helpful:

    I recently ran into an issue where we were consuming a WCF service and using a custom model binder in our ASP.net MVC app. Everything worked fine excerpt when we were serializing our ILists. IList gets serialized to arrays by default. I ended up converting our the arrays back to ILists using Reflection and calling the following method in the custom model binder. Here is how method looks like:

    public object ConvertArraysToIList(object returnObj)    
    {
    
    if (returnObj != null)
    {
        var allProps = returnObj.GetType().GetProperties().Where(p => p.PropertyType.IsPublic 
            && p.PropertyType.IsGenericType 
            && p.PropertyType.Name==typeof(IList<>).Name).ToList();
    
        foreach (var prop in allProps)
        {
            var value = prop.GetValue(returnObj,null);
            //set the current property to a new instance of the IList<>
            var arr=(System.Array)value; 
            Type listType=null;
    
            if(arr!=null)
            {
                listType= arr.GetType().GetElementType();
            }
    
            //create an empty list of the specific type
            var listInstance = typeof(List<>)
              .MakeGenericType(listType)
              .GetConstructor(Type.EmptyTypes)
              .Invoke(null);
    
            foreach (var currentValue in arr)
            {
                listInstance.GetType().GetMethod("Add").Invoke(listInstance, new[] { currentValue });
            }
    
            prop.SetValue(returnObj, listInstance, null);
        }
    }
    
    return returnObj;
    }
    

提交回复
热议问题