How do I deserialize a JSON array and ignore the root node?

tony picture tony · Jan 6, 2014 · Viewed 27.7k times · Source

I have next response from server -

{"response":[{"uid":174952xxxx,"first_name":"xxxx","last_name":"xxx"}]}

I am trying to deserialize this in next way -

JsonConvert.DeserializeObject<T>(json);  

Where T = List of VkUser, but I got error.

[JsonObject]
public class VkUser
{
    [JsonProperty("uid")]
    public string UserId { get; set; }

    [JsonProperty("first_name")]
    public string FirstName { get; set; }

    [JsonProperty("last_name")]
    public string LastName { get; set; }
}

I always tryed

public class SomeDto // maybe Response as class name will fix it but I don't want such name
{
    public List<VkUser> Users {get;set;}
}

What deserialization options can help me?

Answer

Alberto picture Alberto · Jan 6, 2014

Use SelectToken:

string s =  "{\"response\":[{\"uid\":174952,\"first_name\":\"xxxx\",\"last_name\":\"xxx\"}]}";

var users = JObject.Parse(s).SelectToken("response").ToString();

var vkUsers = JsonConvert.DeserializeObject<List<VkUser>>(users);

as pointed out by Brian Rogers, you can use ToObject directly:

var vkUsers = JObject.Parse(s).SelectToken("response").ToObject<List<VkUser>>();