如何使用jsonconvert.deserializeobject与下面的json
[{
"attributes" : {
"type" : "User",
"url" : "/xx/xx/xx"
},
"Id" : "1",
"Name" : "abc"
},{
"attributes" : {
"type" : "User",
"url" : "/xx/xx/xx"
},
"Id" : "2",
"Name" : "abc"
},{
"attributes" : {
"type" : "User",
"url" : "/xx/xx/xx"
},
"Id" : "3",
"Name" : "abc"
}]
这些是我的班级
public class Attributes
{
public string type { get; set; }
public string url { get; set; }
}
public class RootObject
{
public Attributes attributes { get; set; }
public string Id { get; set; }
public string Name { get; set; }
}
我尝试了
var c = JsonConvert.DeserializeObject <RootObject>(jsonText);
您的JSON实际上代表RootObject
实例的数组。尝试以下操作:
var c = JsonConvert.DeserializeObject<RootObject[]>(jsonText);
或可能
var c = JsonConvert.DeserializeObject<List<RootObject>>(jsonText);
甚至
var c = JsonConvert.DeserializeObject<IEnumerable<RootObject>>(jsonText);
您的JSON实际上是一个数组,因此请尝试将其列为RootObject[]
:
var c = JsonConvert.DeserializeObject<RootObject[]>(jsonText);
you json
是一个数组(或集合),请尝试使用数组类型进行对其进行测试:
var c = JsonConvert.DeserializeObject<RootObject[]>(jsonText);
或任何其他类型的集合,用于样本:
var c = JsonConvert.DeserializeObject<IEnumerable<RootObject>>(jsonText);
var c = JsonConvert.DeserializeObject<ICollection<RootObject>>(jsonText);
在这种情况下,请尝试告诉Deserializer您期望的是避难所。根据您当前调用JsonConvert.DeserializeObject Method (String)
的方法的文档,返回.NET对象。
此方法JsonConvert.DeserializeObject<T> Method (String)
返回指定的类型。例如:
public class Attributes
{
public string type { get; set; }
public string url { get; set; }
}
public class RootObject
{
public Attributes attributes { get; set; }
public string Id { get; set; }
public string Name { get; set; }
}
RootObject c = JsonConvert.DeserializeObject<RootObject>(jsonText);