本文介绍了如何反序列化JSON数组并忽略根节点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我收到服务器的下一个响应-
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);
其中T = VkUser的列表,但出现错误.
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; }
}
我一直尝试
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?
推荐答案
使用 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
:
as pointed out by Brian Rogers, you can use ToObject
directly:
var vkUsers = JObject.Parse(s).SelectToken("response").ToObject<List<VkUser>>();
这篇关于如何反序列化JSON数组并忽略根节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!