Reputation:
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"
}
}
Upvotes: 0
Views: 1053
Reputation: 15354
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);
Upvotes: 1