System类型的异常.转换到List<>时出现InvalidCastException异常

本文关键字:异常 InvalidCastException List 类型 转换 System | 更新日期: 2023-09-27 18:03:45

我正在从服务检索Json数据,我尝试这样做之后,但这个异常被抛出。有了这些细节附加信息:无法强制转换"System"类型的对象。对象'到类型'System.Collections.Generic.List ' 1[Sample.Reply]'。有人知道我哪里出错了吗?

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

应答类定义如下

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

Json是这样的

{
"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"
}

}

System类型的异常.转换到List<>时出现InvalidCastException异常

可以看到,您的Reply类只表示replies属性中的对象。你的模型应该是这样的:

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; }
}

现在你可以使用

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