You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Avalonia C#中HttpClient请求API后无法遍历JSON元素的问题

问题解决:Avalonia C#中HttpClient获取JSON后无法遍历的错误

错误原因

你遇到的Unable to apply indexing using [] to an expression of type 'char'错误,本质是因为results是ReadAsStringAsync返回的字符串,直接foreach遍历会逐个取出字符串中的字符,此时result是char类型,自然不能用["name"]来索引取值。

同时你代码里的JsonSerializer.Serialize(response.Content)完全无用,它序列化的是HttpContent对象本身,不是API返回的JSON内容,直接删掉即可。

解决方案

根据你返回的JSON结构(键为字符串、值为服务器信息的对象),有两种处理方式:

方式一:定义实体类+反序列化为字典

这种方式类型安全,推荐使用。

  1. 先定义对应服务器信息的实体类:
public class Server
{
    public string Name { get; set; }
    public string Description { get; set; }
}
  1. 修改API请求方法:
private async Task GetServersInfos()
{
    using (var httpClient = new HttpClient())
    {
        using (var request = new HttpRequestMessage(HttpMethod.Get, "http://example.com/api"))
        {
            var response = await httpClient.SendAsync(request);

            if (response.IsSuccessStatusCode)
            {
                var jsonString = await response.Content.ReadAsStringAsync();
                // 将JSON反序列化为字典,键是"1"、"2"这类字符串,值为Server对象
                var servers = JsonSerializer.Deserialize<Dictionary<string, Server>>(jsonString);

                if (servers != null)
                {
                    // 遍历所有服务器对象
                    foreach (var server in servers.Values)
                    {
                        // 注意:直接赋值会覆盖内容,这里改成拼接所有服务器名称
                        TestText.Text += $"{server.Name}\n";
                    }
                }
            }
        }
    }
}

方式二:使用JsonDocument直接解析(无需定义实体类)

如果不想定义实体类,可以用JsonDocument直接遍历JSON对象的属性:

private async Task GetServersInfos()
{
    using (var httpClient = new HttpClient())
    {
        using (var request = new HttpRequestMessage(HttpMethod.Get, "http://example.com/api"))
        {
            var response = await httpClient.SendAsync(request);

            if (response.IsSuccessStatusCode)
            {
                var jsonString = await response.Content.ReadAsStringAsync();
                using var doc = JsonDocument.Parse(jsonString);
                var root = doc.RootElement;

                // 遍历根对象的所有属性
                foreach (var property in root.EnumerateObject())
                {
                    var serverName = property.Value.GetProperty("name").GetString();
                    TestText.Text += $"{serverName}\n";
                }
            }
        }
    }
}

注意点

原代码中每次循环给TestText.Text赋值会覆盖之前的内容,最后只会显示最后一个服务器的名称,所以示例中改成了拼接的方式,你可以根据需求调整(比如用StringBuilder提升性能,或者绑定到集合控件)。

内容的提问来源于stack exchange,提问作者user5746984

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 03:37:40