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

╄→尐↘猪︶ㄣ 提交于 2019-12-09 02:12:37

问题


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?


回答1:


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>>();


来源:https://stackoverflow.com/questions/20953713/how-do-i-deserialize-a-json-array-and-ignore-the-root-node

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!