我需要写大学名单。我已经写了国家和城市清单。但是在大学中,数据的表示有些不同。有List<string>,我不知道如何处理。我成功地从here获得了国家。从here开始,我需要将大学标题写到{"response":[201,。这是code我如何获得国家的。我在城市中使用的类比代码。尝试执行此行List<string>时,出现了未处理的异常。该类的完整代码:

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

注意,似乎不需要将这些列表存储在静态或类变量中,您只需将它们返回给调用方即可。

10-08 17:15