3

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.

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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

1 Comment

Already tried that, unfortunately that doesn't work, since that will resolve it to properties with camel-cased property names.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.