使用JavaScriptSerializer在c#中反序列化泛型对象数组



我从循环调用rest API,我的对象名称是在运行时决定的。我能够使用反射在这里为一个对象,但如何获得对象列表?

  foreach (CloudDBTableList table in cloudDBTableList)
            {                
               string uri = string.Format(table.URI, "1-Jan-2011");
               string result  = _dataPullSvcAgent.GetData (baseURI + uri);

               string tableClassType = table.TableName + ", " + namespacePrefix;//namespacePrefix is same as assembly name.
               Type t = Type.GetType(tableClassType);
               JavaScriptSerializer jsonDeserializer = new JavaScriptSerializer();
//t is only type of object whereas below method returns List<t> how to put it?
               var objectList = jsonDeserializer.Deserialize(result, t);
            }
            return true;
        }

Stackoverflow Rocks。从这个问题中找到了答案(尽管下面的问题与我的有点不同):-

如何使用反射动态创建通用c#对象?我这样修改了我的代码:-

 foreach (CloudDBTableList table in cloudDBTableList)
            {                
               string uri = string.Format(table.URI, "1-Jan-2011");
               string result  = _dataPullSvcAgent.GetData (baseURI + uri);

               string tableClassType = namespacePrefix + "." + table.SchemaName + "." + table.TableName + ", " + namespacePrefix;//namespacePrefix is same as assembly name.
               Type t = Type.GetType(tableClassType);
               JavaScriptSerializer jsonDeserializer = new JavaScriptSerializer();
               var L1 = typeof(List<>);
               Type listOfT = L1.MakeGenericType(t);
               var objectList = jsonDeserializer.Deserialize(result, listOfT);

            }

您应该能够这样做:

JavaScriptSerializer jsonDeserializer = new JavaScriptSerializer();
List<CloudDBTableList > list= jsonDeserializer.Deserialize<List<CloudDBTableList>>(cloudDBTableList);

相关内容

  • 没有找到相关文章

最新更新