C# RESTAPI-模型绑定时如何将属性从int/string转换为string?

C# RESTAPI-模型绑定时如何将属性从int/string转换为string?,c#,json,json.net,asp.net-core-3.1,model-binding,C#,Json,Json.net,Asp.net Core 3.1,Model Binding,在我的API中,我使用Refit创建了一个客户端来调用第三方API。问题是第三方API返回的数据不一致。它返回城市名称和邮政编码,但有时是int或字符串: { "input": "Pa", "cities": [ { "code": "09100", "city": "PAMIERS" }, {

在我的API中,我使用Refit创建了一个客户端来调用第三方API。问题是第三方API返回的数据不一致。它返回城市名称和邮政编码,但有时是int或字符串:

{
"input": "Pa",
"cities": [
    {
        "code": "09100",
        "city": "PAMIERS"
    },
    {
        "code": "09130",
        "city": "PAILHES"
    },
    {
        "code": 10100,
        "city": "PARS LES ROMILLY"
    },
    {
        "code": 10160,
        "city": "PAISY COSDON"
    },
    {
        "code": 10210,
        "city": "PARGUES"
    }
]
}
所以我创建了这个路线:

public async Task<IActionResult> SearchCity([FromForm] CitySearch data)
{
    var api = RestService.For<ICityAPI>("https://vicopo.selfbuild.fr");
    try
    {
        var search = await api.SearchCityListAsync(data.search);
        return Ok(search);
    }
    catch (Exception ex)
    {
        return StatusCode(StatusCodes.Status502BadGateway, ex);
    }
}
公共异步任务搜索城市([FromForm]城市搜索数据)
{
var api=RestService.For(“https://vicopo.selfbuild.fr");
尝试
{
var search=await api.searchcitylstatsync(data.search);
返回Ok(搜索);
}
捕获(例外情况除外)
{
返回状态码(StatusCodes.Status502BadGateway,ex);
}
}
使用此客户端的用户:

public interface ICityAPI
{
    [Get("/search/{search}")]
    Task<CityList> SearchCityListAsync(string search);
}
公共接口ICityAPI
{
[获取(“/search/{search}”)]
任务搜索城市同步(字符串搜索);
}
要最终将收到的Json绑定到此模型,请执行以下操作:

public class CityList
{
    [JsonProperty("cities")]
    public List<City> Cities { get; set; }
}

public class City
{
    [JsonProperty("city")]
    public string city { get; set; }

    [JsonProperty("code")]
    public string code { get; set; }
}
公共类城市列表
{
[JsonProperty(“城市”)]
公共列表城市{get;set;}
}
公营城市
{
[JsonProperty(“城市”)]
公共字符串city{get;set;}
[JsonProperty(“代码”)]
公共字符串代码{get;set;}
}

当这个Json不是常量时,我如何将它绑定到我的模型?

一种“快速且不干净”的方法是将属性更改为
对象
,例如:
公共对象代码{get;set;}
。否则,您必须创建一个自定义JSON转换器,即使这样,最终的类型是什么?可能前导零并不重要,您可以删除它们并存储为
int
;但是,也许不是——那么您只需将所有内容存储为
string
。您知道您使用的是什么JSON序列化程序吗?您已经用
[JsonProperty]
注释了您的模型,这表明您使用的是Json.NET,而Json.NET正好可以使用。只要声明
公共字符串代码
,int值就会自动反序列化为字符串。看见那么,你到底有什么问题?您可以共享一个字符串吗?顺便提一下,
“09130”
必须是字符串的原因是JSON标准不允许在整数文本中使用前导零(我相信是为了避免与JavaScript八进制文本混淆)。