我收到伺服器的下一个回应-

{"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;}
}

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

最佳答案

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

关于c# - 如何反序列化JSON数组并忽略根节点?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20953713/

10-13 08:20