1

I created a generic function that retreives a JSON and parses it:

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

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

        return values;
    }

The problem that i have alot of Classes that uses this. for example when i try to use this:

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

I get InvalidCastException Unable to cast object of type 'System.Collections.Generic.List[System.Object]' to type 'System.Collections.Generic.IList[Receipt]'.

Anyway to keep my function Generic and be able to cast it to all of my classes/models?


Make your function generic:

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

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

        return values;
    }
4

2 回答 2

6

使您的功能通用:

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

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

        return values;
    }
于 2012-06-16T13:43:43.427 回答
4

If the object is deserialized as Receipt, you could use Enumerable extensions.

IList<Receipt> receipts = RetrieveView(result).Cast<Receipt>().ToList();
于 2012-06-16T13:43:49.620 回答