Reputation: 254
How to use JsonConvert.DeserializeObject with below 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"
}]
These are my class
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; }
}
I have tried with
var c = JsonConvert.DeserializeObject <RootObject>(jsonText);
Upvotes: 1
Views: 687
Reputation: 502
Try telling the deserializer what you're expecting to deserialize to, in this case RootObject.
According to the documentation of the method you're currently calling JsonConvert.DeserializeObject Method (String)
returns a .net object.
While this method JsonConvert.DeserializeObject<T> Method (String)
returns the specified type.
for example:
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);
Upvotes: 0
Reputation: 38598
You json
is a array (or collection), try to deserialize it using the array type:
var c = JsonConvert.DeserializeObject<RootObject[]>(jsonText);
Or any other type of collection, for sample:
var c = JsonConvert.DeserializeObject<IEnumerable<RootObject>>(jsonText);
var c = JsonConvert.DeserializeObject<ICollection<RootObject>>(jsonText);
Upvotes: 1
Reputation: 125610
Your JSON is actually an array, so try deserializing it into RootObject[]
:
var c = JsonConvert.DeserializeObject<RootObject[]>(jsonText);
Upvotes: 3
Reputation: 148980
Your Json actually represents an array of RootObject
instances. Try this:
var c = JsonConvert.DeserializeObject<RootObject[]>(jsonText);
Or possibly
var c = JsonConvert.DeserializeObject<List<RootObject>>(jsonText);
Or even
var c = JsonConvert.DeserializeObject<IEnumerable<RootObject>>(jsonText);
Upvotes: 7