REST API - How to convert a property from int/string to string when model binding?

Viewed 614

In my API, I created a client using Refit to call a third party API. The problem is that the third party API is returning inconsistent data. It returns city names and postcodes but sometimes these are int or strings :

{
"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"
    }
]
}

So I created this route :

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);
    }
}

Who uses this client :

public interface ICityAPI
{
    [Get("/search/{search}")]
    Task<CityList> SearchCityListAsync(string search);
}

To finally bind the received Json to this model :

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; }
}

How can I bind this Json to my model when it is not constant?

0 Answers
Related