简体   繁体   中英

ASP.NET Core 3.1: How to deserialize camelcase json from webapi to pascalcase

the default WebApi template for ASP.NET 3.1 produces a service that returns weather forecasts in camel-cased JSON format.

If I want to consume this service in an ASP.NET 3.1 web application, but have no access to the web service, how do I deserialize the camel-cased JSON into an object that is pascal-cased?

So deseialize this WebAPI output:

{
    "date": "2020-10-14T13:45:55.9398376+01:00",
    "temperatureC": 43,
    "temperatureF": 109,
    "summary": "Bracing"
}

to this object:

public class WeatherForecast
{
    public DateTime Date { get; set; }
    public int TemperatureC { get; set; }
    public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
    public string Summary { get; set; }
}

If I had access to both service and site it's a simple matter of setting the JSON contract resolver.

You can add the JsonProperty attribute for this.

public class WeatherForecast
{
    [JsonProperty(PropertyName = "date")]
    public DateTime Date { get; set; }
    [JsonProperty(PropertyName = "temperatureC")]
    public int TemperatureC { get; set; }
    [JsonProperty(PropertyName = "temperatureF")]
    public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
    [JsonProperty(PropertyName = "summary")]
    public string Summary { get; set; }
}

Alteratively, add the Microsoft.AspNetCore.Mvc.NewtonsoftJson Nuget package in your project. Then, in the Startup.cs class, include the following lines:

services.AddControllers().AddNewtonsoftJson();
services.Configure<MvcNewtonsoftJsonOptions>(options =>
{
    options.SerializerSettings.ContractResolver = new 
               CamelCasePropertyNamesContractResolver();
});

So after trying a few things the following code worked for me:

public async Task<IEnumerable<WeatherForecast>> GetWeatherForecastsAsync()
{
    var httpClient = this.httpClientFactory.CreateClient("retryable");
    using var response = await httpClient.GetAsync(Endpoint);
    response.EnsureSuccessStatusCode();
    var responseStream = await response.Content.ReadAsStreamAsync();
    return await JsonSerializer.DeserializeAsync<IEnumerable<WeatherForecast>> 
    (responseStream, new JsonSerializerOptions { PropertyNamingPolicy = 
    JsonNamingPolicy.CamelCase });
}

Basically I wasn't passing any options to the JsonSerializer when deserializing the response stream. Adding the CamelCase JSON naming policy worked.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM