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

AspNet Core API如何返回指定格式的去重国家及城市集合数据

实现方案

你当前返回字符串数组的核心原因是直接投影了字符串类型,ASP.NET Core序列化时会直接输出纯字符串集合,你只要投影为包含对应属性的对象即可,以下是两种可行实现:

方案1:使用匿名类快速实现(无需额外建类)

1.1 国家列表接口修改

[HttpGet("countries")]
public async Task<ActionResult<IEnumerable<object>>> GetCountries()
{
    return await _context.Location
        .Select(x => new { country = x.Country })
        .Distinct()
        .ToListAsync();
}

这里直接在Select中构造匿名对象,属性名直接写为小写country即可匹配你期望的JSON键名。

1.2 城市列表接口实现

[HttpGet("cities/{country}")]
public async Task<ActionResult<IEnumerable<object>>> GetCites(string country)
{
    return await _context.Location
        .Where(x => x.Country.Equals(country, StringComparison.OrdinalIgnoreCase)) // 可按需调整是否忽略大小写匹配国家
        .Select(x => new { city = x.City })
        .Distinct()
        .ToListAsync();
}

方案2:使用DTO类实现(更规范,适合大型项目)

先定义两个传输对象:

using System.Text.Json.Serialization;

// 国家返回DTO
public class CountryResponse
{
    [JsonPropertyName("country")] 
    // 如果你全局配置了驼峰命名可省略该特性,直接写属性名为Country即可
    public string Country { get; set; }
}

// 城市返回DTO
public class CityResponse
{
    [JsonPropertyName("city")]
    public string City { get; set; }
}

然后修改对应接口:

国家接口

[HttpGet("countries")]
public async Task<ActionResult<IEnumerable<CountryResponse>>> GetCountries()
{
    return await _context.Location
        .Select(x => new CountryResponse { Country = x.Country })
        .Distinct()
        .ToListAsync();
}

城市接口

[HttpGet("cities/{country}")]
public async Task<ActionResult<IEnumerable<CityResponse>>> GetCites(string country)
{
    return await _context.Location
        .Where(x => x.Country == country)
        .Select(x => new CityResponse { City = x.City })
        .Distinct()
        .ToListAsync();
}

可选全局配置:如果你需要所有接口都默认返回驼峰格式的JSON键,可以在Program.cs中添加配置:

builder.Services.AddControllers()
    .AddJsonOptions(options =>
    {
        options.JsonSerializerOptions.PropertyNamingPolicy = System.Text.Json.JsonNamingPolicy.CamelCase;
    });

配置后DTO的大写属性名会自动序列化为小写开头的驼峰格式,无需单独加JsonPropertyName特性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 19:54:05