【问题标题】:Web Api serializer serialize object to camel-case jsonWeb Api 序列化器将对象序列化为驼峰式 json
【发布时间】:2022-01-29 16:18:59
【问题描述】:

请考虑以下代码:

var ResultMaster = new Master()
{
    Id = Result.Id,
    CityCode = Result.CityCode,
    Desc = Result.Desc,
    EmployeeId = Result.EmployeeId,
    IsDelete = Result.IsDelete,
    LastChange = Result.LastChange,
    StateCode = Result.StateCode,
};

return Ok(ResultMaster);

当我调用我的 Web API 方法时,我得到的是驼峰式 json:

'{"id":1,"cityCode":"001","desc":null,"employeeId":36648,"isDelete":false,"lastChange":"2021-11-25","stateCode":"01"}'

所以我可以使用反序列化它

System.Text.Json.JsonSerializer.Deserialize<T>

public static async Task<T?> GetObjectFromResponse<T>(this Task<HttpResponseMessage> responseMessage)
{
      var Response = await responseMessage;
      string StringContent = await Response.Content.ReadAsStringAsync();
      var Obj = JsonSerializer.Deserialize<T>(StringContent);
      //var Obj = JsonSerializer.Deserialize<T>("{\"Id\":1,\"CityCode\":\"001\",\"Desc\":null,\"EmployeeId\":36648,\"IsDelete\":false,\"LastChange\":\"2021-11-25\",\"StateCode\":\"01\"}");
      return Obj;
}

我在我的 Blazor WASM 中这样调用上述方法:

var Master = await _httpClient.GetAsync($"/api/Ques/GetObject?id={id}").GetObjectFromResponse<MasterDTO>();
return Master;

我 qet 为空 Master 对象(不为空)。但是,如果我将属性名称更改为 Pascal-case(上面的注释代码),那么我会得到正确的对象。

如何为我的 API 序列化程序设置配置保留属性名称?

谢谢

【问题讨论】:

  • 使用 Newtonsoft 即可。 Json 序列化器。使用 Ms 序列化程序,您的问题才刚刚开始。
  • 您比较 Newtonsoft 和 Microsoft?有太阳的小麦种子?
  • 这个太阳迟早要购买小麦种子,就像许多其他技术一样。现在大多数只有青少年在为 MS 工作。所以质量越来越差。
  • 小麦种子需要阳光才能开花

标签: c# asp.net-web-api serialization blazor system.text.json


【解决方案1】:

只需将此代码添加到ConfigureServices 部分:

services.AddControllers()
        .AddJsonOptions(options => 
        {
            options.JsonSerializerOptions.PropertyNamingPolicy = null;
        });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-09
    • 2013-01-09
    • 1970-01-01
    • 1970-01-01
    • 2014-01-30
    • 1970-01-01
    • 2010-10-08
    相关资源
    最近更新 更多