如何在c#反序列化json中获取数组的所有元素
本文关键字:数组 元素 获取 反序列化 json | 更新日期: 2023-09-27 18:19:13
在c#中,我有5-6天的时间,我想尝试使用api一个站点。反序列化JSON,格式为
({"uid":1476402,:"first_name ",:"last_name ","域":"sandrische","在线":1、"user_id":1476402},{"uid":3813182,:"first_name ",:"last_name ","域":"id3813182","在线":0,"user_id":3813182},{"uid":12789624,:"first_name ",:"last_name ","域":"id12789624","在线":0,"user_id":12789624}]
有一个类
public class vkResponse
{
[JsonProperty(PropertyName = "uid")]
public int Id { get; set; }
[JsonProperty(PropertyName = "first_name")]
public string FirstName { get; set; }
[JsonProperty(PropertyName = "last_name")]
public string LastName { get; set; }
[JsonProperty(PropertyName = "photo_50")]
public Uri PhotoUri { get; set; }
[JsonProperty(PropertyName = "online")]
[JsonConverter(typeof(BoolConverter))]
public bool IsOnline { get; set; }
[JsonProperty(PropertyName = "lists")]
public List<int> Lists { get; set; }
}
public class BoolConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteValue(((bool)value) ? 1 : 0);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
return reader.Value.ToString() == "1";
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(bool);
}
}
我想得到id
var req = new HttpRequest();
string resp = req.Get("https://api.vk.com/method/friends.get?user_ids=1&fields=domain&access_token=" + GetToken()).ToString();
JObject o = JObject.Parse(resp);
JArray array = (JArray)o["response"];
vkResponse v = JsonConvert.DeserializeObject<vkResponse>(array.First().ToString());
richTextBox1.Text = v.Id.ToString();
但是我只得到第一个ID,如何得到所有的ID?我认为这个array.First().ToString()
的问题是什么?
var v = JsonConvert.DeserializeObject<IEnumerable<vkResponse>>(array.ToString());
var userids = v.Select(x=>x.id);
您的响应是vkResponse
类的数组,因此您可以将其反序列化为c#数组:
vkResponse[] vkResponses = JsonConvert.DeserializeObject<vkResponse[]>(array.ToString());
一旦你有了数组,你就可以遍历并访问每个元素的id。
请给我一个例子如何遍历和访问每个元素的id
好的,这里有一种方法可以使用基本的c#循环结构和数组来实现:
vkResponse[] vkResponses = JsonConvert.DeserializeObject<vkResponse[]>(array.ToString());
if (vkResponses == null)
throw new JsonException();
int [] ids = new int[vkResponses.Length];
for (int i = 0; i < vkResponses.Length; i++)
{
ids[i] = vkResponses[i].Id;
}
如果希望在富文本框中以逗号分隔的整数序列显示id,则使用以下方法生成字符串:
public static string ExtractVkResponseIds(string vkResponseJson)
{
vkResponse[] vkResponses = JsonConvert.DeserializeObject<vkResponse[]>(vkResponseJson);
if (vkResponses == null)
throw new JsonException();
StringBuilder sb = new StringBuilder();
// Format the ids as a comma separated string.
foreach (var response in vkResponses)
{
if (sb.Length > 0)
sb.Append(System.Globalization.CultureInfo.CurrentCulture.TextInfo.ListSeparator);
sb.Append(response.Id.ToString());
}
return sb.ToString();
}
并命名为:
var req = new HttpRequest();
string resp = req.Get("https://api.vk.com/method/friends.get?user_ids=1&fields=domain&access_token=" + GetToken()).ToString();
JObject o = JObject.Parse(resp);
JArray array = (JArray)o["response"];
string ids = ExtractVkResponseIds(array.ToString());
richTextBox1.Text = ids;
顺便说一下,我使用了本地化的ListSeparator,在你的语言中可能不是逗号。如果需要,您可以将其更改为字面逗号。
顺便说一下,您的示例Json字符串缺少右括号("]")。