我需要写信给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;
}
}
}
答案 0 :(得分:3)
你的问题是返回的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。
注意似乎没有必要将这些列表存储在静态或类变量中 - 您只需将它们返回给调用者即可。