【问题标题】:ASP.NET Core 3.1: How to deserialize camelcase json from webapi to pascalcaseASP.NET Core 3.1:如何将camelcase json从webapi反序列化为pascalcase
【发布时间】:2021-01-27 19:45:58
【问题描述】:

ASP.NET 3.1 的默认 WebApi 模板生成的服务以驼峰格式 JSON 格式返回天气预报。

如果我想在 ASP.NET 3.1 Web 应用程序中使用此服务,但无法访问该 Web 服务,我如何将骆驼大小写的 JSON 反序列化为帕斯卡大小写的对象?

所以反序列化这个 WebAPI 输出:

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

到这个对象:

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

如果我可以同时访问服务和站点,那么设置 JSON 合同解析器就很简单了。

【问题讨论】:

    标签: c# json asp.net-core asp.net-core-mvc asp.net-core-webapi


    【解决方案1】:

    您可以为此添加 JsonProperty 属性。

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

    【讨论】:

      【解决方案2】:

      或者,在您的项目中添加 Microsoft.AspNetCore.Mvc.NewtonsoftJson Nuget 包。然后,在 Startup.cs 类中,包含以下几行:

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

      【讨论】:

      • 已经尝试过了,不幸的是这不起作用,因为这会将其解析为具有驼峰属性名称的属性。
      【解决方案3】:

      所以在尝试了一些事情之后,以下代码对我有用:

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

      在反序列化响应流时,基本上我没有将任何选项传递给 JsonSerializer。添加 CamelCase JSON 命名策略有效。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-31
        • 1970-01-01
        • 1970-01-01
        • 2021-11-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多