2012-06-16 104 views
1

我創建了一個retreives JSON和分析它的通用功能:將IList <Object>投射到IList <CustomObject>?

public IList<Object> RetrieveView(string result) 
    { 
     JavaScriptSerializer ser = new JavaScriptSerializer(); 

     IList<Object> values = ser.Deserialize< IList<Object> >(result); 

     return values; 
    } 

,我有很多使用這個類的問題。 例如,當我嘗試使用此:

IList<Receipt> receipts = (IList<Receipt>)RetrieveView(result); 

我得到InvalidCastExceptionUnable to cast object of type 'System.Collections.Generic.List[System.Object]' to type 'System.Collections.Generic.IList[Receipt]'.

反正讓我的通用功能,並能夠將其轉換爲我所有的類/型號的?

+0

你的JSON的外觀和你的'Reciept'類是什麼? –

回答

6

讓你的函數通用:

public IList<T> RetrieveView<T>(string result) 
    { 
     JavaScriptSerializer ser = new JavaScriptSerializer(); 

     IList<T> values = ser.Deserialize< IList<T> >(result); 

     return values; 
    } 
4

如果對象進行反序列化的收據,你可以使用可枚舉擴展。

IList<Receipt> receipts = RetrieveView(result).Cast<Receipt>().ToList(); 
+0

是的!如果可以的話,1000票。 – bwperrin

相關問題