gpt4 book ai didi

c# - 从 VK API 解析大学

转载 作者:太空宇宙 更新时间:2023-11-03 23:01:27 24 4
gpt4 key购买 nike

我需要写信给List<string>大学名单。我已经写好了要列出的国家和城市。但在大学中,数据的表现略有不同。有 {"response":[201,我不知道如何处理它。我成功地从 here 得到了国家.来自here我需要将大学名称写到 List<string> .这是 code我是怎么得到国家的。我在城市中使用的类比代码。在尝试执行此行时 var universityRepository = new RootObject((int)universityInResponse["id"], (string)universityInResponse["title"]);我有一个未处理的异常。类的完整代码:

public class GettingUniversity
{
public static List<RootObject> listOfUniversitiesRoot = new List<RootObject>();//This List contains Id and Titles of universities
public List<string> listOfUniversities = new List<string>();//list with names of the universities
private string jsonString; //string for getting data from the url
public async Task<List<RootObject>> FetchAsync(string url)
{
//getting data process goes here
using (var httpClient = new System.Net.Http.HttpClient())
{
var stream = await httpClient.GetStreamAsync(url);
StreamReader reader = new StreamReader(stream);
jsonString = reader.ReadToEnd();
}

var responseUniversities = JArray.Parse(JObject.Parse(jsonString)["response"].ToString());//parsing data from jsonstring

foreach (var universityInResponse in responseUniversities)//the foreach-loop
{
var universityRepository = new RootObject((int)universityInResponse["id"], (string)universityInResponse["title"]);
//listOfUniversitiesRoot.Add(universityRepository);//adding to the list with names of the universities
//listOfUniversities.Add(universityRepository.Title);
}

return listOfUniversitiesRoot;//returned list
}

属性在这里表示:

namespace KoshelnykTestTask
{
//Here I have set properties for FetchAsync(string url) to get countries and cities
public class RootObject
{
public int Id { get; set; }
public string Title { get; set; }
public RootObject(int Id, string Title)
{
this.Id = Id;
this.Title = Title;
}
}
}

最佳答案

您的问题是返回的 JSON 包含一个多态数组——第一个条目是一个整数,其余是包含大学信息的对象:

{
"response":[
201,
{
"id":1096,
"title":"КПИ им. И. Сикорского"
},
{
"id":1135,
"title":"НУФВСУ (бывш. КГИФК)"
},
{
"id":1140,
"title":"КГАВТ им. Конашевича-Сагайдачного"
},

在反序列化对象之前,需要对整型值进行过滤,可以按如下方式进行:

var universityRepository  = JToken.Parse(jsonString)["response"]
// Filter the integer value by selecting only objects
.OfType<JObject>()
// Deserialize each object to a RootObject
.Select(o => o.ToObject<RootObject>())
// Return in a List<RootObject>
.ToList();

var listOfUniversities = universityRepository
.Select(u => u.Title)
.ToList();

样本 fiddle .

请注意,似乎没有必要将这些列表存储在静态或类变量中——您可以简单地将它们返回给调用者。

关于c# - 从 VK API 解析大学,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42939991/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com