Json 反序列化无法访问对象的属性
本文关键字:对象 属性 访问 反序列化 Json | 更新日期: 2023-09-27 18:33:07
我得到了这个类(通过使用json2c#):
public class Friends
{
public class Datum
{
public string name { get; set; }
public string id { get; set; }
}
public class Paging
{
public string next { get; set; }
}
public class Summary
{
public int total_count { get; set; }
}
public class RootObject
{
public List<Datum> data { get; set; }
public Paging paging { get; set; }
public Summary summary { get; set; }
}
}
这是我进行反序列化的可怜尝试:
DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(Friends));
MemoryStream ms = new MemoryStream(System.Text.ASCIIEncoding.ASCII.GetBytes(data));
Friends x = (Friends)js.ReadObject(ms);
例如,我以为我应该能够访问 Friends.Datum.name 但它不起作用。
我的问题是,我做错了什么?我应该如何优化我的代码?
我已经为我的 ListView 获得了一个数据模板,并且我正在使用 MVVM 模式,因此绑定应该不是大问题。
下面是一个示例 json 响应:
{"data":[{"name":"XXX","id":"XXX"}],"paging":{"next":"https:'/'/graph.facebook.com'/v2.5'/XXX'/friends?access_token=X"},"summary":{"total_count":2}}
XXX是秘密
您必须将
反序列化程序与RootObject
的类型一起使用,因为它具有匹配的属性 data
、 paging
和 summary
。
如果您尝试反序列化 RootObject 而不是 Friends 对象,则代码应该有效。还要记住使用 using 语句来确保在流上调用 Dispose。
DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(RootObject));
using (MemoryStream ms = new MemoryStream(System.Text.ASCIIEncoding.ASCII.GetBytes(data)));
{
RootObject x = (RootObject)js.ReadObject(ms);
}
然后你可以像
x.summary.total_count