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

在MVC C#中使用Newtonsoft反序列化嵌套JSON并绑定下拉列表问题

解决世界银行API嵌套JSON反序列化问题

我看你现在的核心问题是用了适配Google搜索API的解析代码来处理世界银行的API返回,但这两个接口的JSON结构完全不一样,自然会出问题!

先理清世界银行API的返回结构

它返回的是一个顶级数组,里面包含两个核心元素:

  • 第一个元素是分页元数据(包含page、pages、total这类信息)
  • 第二个元素才是你需要的国家数据集合,每个国家对象里的id就是你要提取的内容

修正后的解析与绑定代码

下面给你两种实用方案,按需选择:

方案1:快速提取ID(无需实体类)

如果只是要提取country id绑定到下拉列表,不需要完整的实体类,直接遍历即可:

// 假设googleSearchText是你从API获取到的JSON字符串
JArray worldBankData = JArray.Parse(googleSearchText);
// 定位到国家数据数组(数组的第二个元素,索引为1)
IList<JToken> countryTokens = worldBankData[1].Children().ToList();

// 提取所有国家ID
List<string> countryIds = new List<string>();
foreach (JToken country in countryTokens)
{
    string countryId = country["id"].ToString();
    countryIds.Add(countryId);
}

// 绑定到DropdownList
dropdownList.DataSource = countryIds;
dropdownList.DataBind();

方案2:用实体类反序列化(更规范)

如果后续还需要用到国家名称、区域等其他信息,建议先定义对应的实体类:

public class Country
{
    public string id { get; set; }
    public string iso2Code { get; set; }
    public string name { get; set; }
    // 若需要其他字段(比如region、incomeLevel),可以继续添加对应属性
}

然后反序列化并绑定:

JArray worldBankData = JArray.Parse(googleSearchText);
IList<JToken> countryTokens = worldBankData[1].Children().ToList();

List<Country> countries = new List<Country>();
foreach (JToken country in countryTokens)
{
    Country c = country.ToObject<Country>();
    countries.Add(c);
}

// 绑定到DropdownList,这里可以设置显示名称、存储ID
dropdownList.DataTextField = "name";
dropdownList.DataValueField = "id";
dropdownList.DataSource = countries;
dropdownList.DataBind();

关键问题点总结

  • 世界银行API返回的是数组而非单个对象,所以必须用JArray.Parse解析,不能用JObject.Parse
  • 国家数据在数组的第二个元素(索引1),和Google API的responseData.results路径完全不同
  • 绑定下拉列表时,用实体类方案可以同时实现“显示国家名称+存储ID”的需求,更灵活

内容的提问来源于stack exchange,提问作者Héctor Morales

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 09:08:53