如何反序列化JSON数组并忽略根节点?

时间:2014-01-06 15:50:09

标签: c# json json.net deserialization

我有来自服务器的下一个回复 -

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

我试图以下一种方式反序化 -

JsonConvert.DeserializeObject<T>(json);  

其中T = VkUser列表,但我收到错误。

[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; }
}

我总是试着

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

哪些反序列化选项可以帮助我?

1 个答案:

答案 0 :(得分:44)

使用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);

正如Brian Rogers所指出的,您可以直接使用ToObject

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