简体   繁体   中英

An exception of type System.InvalidCastException while casting to a List<>

I am retrieving Json data from a service and I try to do this afterwards but this exception gets thrown. with this details Additional information: Unable to cast object of type 'System.Object' to type 'System.Collections.Generic.List`1[Sample.Reply]'. does anyone know what am getting wrong.

private List<Reply> CreateListFromJson(Stream stream)
    {
        var ser = new DataContractJsonSerializer(typeof(List<Reply>));
        var replies = (List<Reply>)ser.ReadObject(stream);
        return replies;
    }

The reply class is defined as this

public class Reply
{
    public string comment { get; set; }
    public string username { get; set; }
    public string profile_pic { get; set; }
}

and this is what the Json looks like

{
"status": "OK",
"Error": "None",
"Reason": "successful",
"details": {
    "replies": [
        {
            "comment": "great",
            "username": "Crimson Kajes",
            "profile_pic": "http://ibotv.iboapis.com/profile/20130506_044930.jpg"
        },
        {
            "comment": "great",
            "username": "Crimson Kajes",
            "profile_pic": "http://ibotv.iboapis.com/profile/20130506_044930.jpg"
        },
        {
            "comment": "wonderful",
            "username": "Crimson Kajes",
            "profile_pic": "http://ibotv.iboapis.com/profile/20130506_044930.jpg"
        },
        {
            "comment": "wow",
            "username": "Crimson Kajes",
            "profile_pic": "http://ibotv.iboapis.com/profile/20130506_044930.jpg"
        },
        {
            "comment": "thank God",
            "username": "Crimson Kajes",
            "profile_pic": "http://ibotv.iboapis.com/profile/20130506_044930.jpg"
        }
    ],
    "totalreply": "5"
}

}

As you can see, your Reply class only represents the objects in replies property. Your model should be something like this:

public class Reply
{
    public string comment { get; set; }
    public string username { get; set; }
    public string profile_pic { get; set; }
}

public class Details
{
    public List<Reply> replies { get; set; }
    public string totalreply { get; set; }
}

public class RootObject
{
    public string status { get; set; }
    public string Error { get; set; }
    public string Reason { get; set; }
    public Details details { get; set; }
}

Now you can use

var ser = new DataContractJsonSerializer(typeof(RootObject));
var root = (RootObject)ser.ReadObject(stream);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM