将国家/地区写入VK API的列表 [英] Writing countries to a list from VK API

查看:119
本文介绍了将国家/地区写入VK API的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将VK API的国家/地区标题写到以下

I need to write the titles of the countries from VK API to a list from the following link.

我写了一些代码:

public class GettingCountry
{
    public async Task<string> FetchAsync(string url)
    {
        string jsonString;
        using (var httpClient = new System.Net.Http.HttpClient())
        {
            var stream = await httpClient.GetStreamAsync(url);
            StreamReader reader = new StreamReader(stream);
            jsonString = reader.ReadToEnd();
        }

        var readJson = JObject.Parse(jsonString);
        string countryName = readJson["response"]["items"].ToString();
        var deserialized = JsonConvert.DeserializeObject<RootObject>(jsonString);

        return jsonString;
    }
}

public class Item
{
    public int id { get; set; }
    public string title { get; set; }
}

public class Response
{
    public int count { get; set; }
    public List<Item> items { get; set; }
}

public class RootObject
{
    public Response response { get; set; }
}

}

我为此设置了一个断点并进入了string countryName:

I put a breakpoint and got in string countryName only this:

推荐答案

如您所见,VK API返回了一个对象数组. 您的 jsonString 包含完整的响应字符串.现在, jsonString ["response"] ["items"] 包含一组项目.

As you can see the VK API returns you an array of objects. Your jsonString contains full response string. Now, jsonString["response"]["items"] contains an array of items.

首先,您需要解析数组,然后解析每个项目,像这样:

First you need to parse the array and then parse each item, like this:

var readJson = JObject.Parse(jsonString);
JArray countries = JArray.Parse(readJson["response"]["items"]);

var Response listOfCountries = new Response();

foreach (var country in countries) {
    Item currentCountry = new Item();
    currentCountry.id = country.id;
    currentCountry.title = country.title;
    listOfCountries.items.Add(currentCountry);
}

listOfCountries.count = listOfCountries.items.Count;

从代码角度来看,我建议给变量,类和类型取适当的名称,以提高代码的可读性和整洁度.最重要的是,我没有看到单独的 Response 类的意义.例如,您可以重命名您的 Item 类,并将其命名为 Country .然后,您只需要列出一个国家/地区即可.另外,由于您使用的是 async 方法,因此您想在 中使用 对退货进行处理 HttpClient -如果您不这样做,客户端可能会被抛弃得太早,并且您可能会开始遇到非常奇怪的错误.像这样:

From the code perspective, I would recommend giving proper names to variables, classes, and types to improve code readability and cleanliness. On top of it, I don't really see a point in having a separate Response class. For example, you could rename your Item class and call it Country. All you need to have is a list of countries then. Also, because you're using async method, you want to do the processing of the return within your using for the HttpClient - if you don't the client might be disposed too soon and you might start hitting very weird bugs. Like this:

public class VkCountry
{
    public int Id { get; }
    public string Title { get; }
    public VkCountry(int countryId, string countryTitle) {
        this.Id = countryId;
        this.Title = countryTitle;
    }
}

public async Task<List<VkCountry>> FetchAsync(string url)
{
    string jsonString;
    using (var httpClient = new System.Net.Http.HttpClient())
    {
        var stream = await httpClient.GetStreamAsync(url);
        StreamReader reader = new StreamReader(stream);
        jsonString = reader.ReadToEnd();

        var listOfCountries = new List<VkCountry>();

        var responseCountries = JArray.Parse(JObject.Parse(jsonString)["response"]["items"].ToString());

        foreach (var countryInResponse in responseCountries) {
            var vkCountry = new VkCountry((int)countryInResponse["id"], (string)countryInResponse["title"]);

            listOfCountries.Add(vkCountry);
        }

        return listOfCountries;
    } 
}

您可能会注意到,我已经使 VkContry 实现不可变,这些属性是只读的,并且只能使用构造函数进行设置.我建议您在使用相对静态的第三方API时使用不可变的对象(国家/地区列表绝对是静态的,除非某种应用程序逻辑会要求您更新国家/地区的名称). 显然,您可能想添加可空性检查和其他验证.

You might notice that I've made VkContry implementation immutable, the properties are read-only and can be set using the constructor only. I'd recommend using immutable objects when you are consuming relatively static third-party APIs (list of countries is definitely static, unless some kind of application logic will require you to update the name of the country). Obviously, you might want to add nullability checks and different validations.

这篇关于将国家/地区写入VK API的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆