我正在从服务中检索Json数据,之后尝试执行此操作,但抛出此异常。有了这个细节 附加信息:无法将类型为'System.Object'的对象强制转换为'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"
}
}
答案 0 :(得分:1)
如您所见,您的Reply
类仅代表回复属性中的对象。你的模型应该是这样的:
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);