【问题标题】:JSON returns properties in PascalCase instead of camelCaseJSON 在 PascalCase 而不是 camelCase 中返回属性
【发布时间】:2018-08-24 19:44:07
【问题描述】:

使用Microsoft.AspNetCOre.OData 7.0.1,如果我有一个不在数据库中的模型列表,JSON 结果总是以 PascalCase 而不是 camelCase 的形式返回。我怎样才能让我的列表成为驼峰式?

下面的相关例子:

我的模型不在数据库中。

public class Widget 
{
   public string Id { get; set; }
   public string Name { get; set; }
}

我的控制器

[Route("api/[controller]")]
public class WidgetController : ODataController 
{
    [EnableQuery()]
    public IActionResult GetWidgets() 
    {
        // Create list of ten Widgets
        var widgetsList = new List<Widget>();

        for(var i = 0; i < 10; i++) {
            widgetsList.Add(new Widget() { Id = i, Name = $"Widget {i}" });
        }

        return this.Ok(widgetsList);
    }       
}

/api/GetWidgets?$select=name 以以下格式返回

{ Name: "Widget" } 

【问题讨论】:

  • 由于IdName 都是private(因此它们根本不会被序列化为JSON),因此返回的数据与您的代码不匹配。请发帖minimal reproducible example
  • 您需要显式的Json转换器将结果转换为相关案例
  • 可以使用newtonsoft的json.net序列化成camelCase。这里有很多答案 - stackoverflow.com/questions/19445730/…

标签: c# asp.net-core odata


【解决方案1】:

选项 1

即使Widget 不在数据库中,您也可以将其添加到实体数据模型 (EDM)。 EDM 可能有骆驼案作为其惯例。 Widget 将采用该约定。

var builder = new ODataConventionModelBuilder();
builder.EnableLowerCamelCase();

builder.EntitySet<Widget>("Widgets");

_edmModel = builder.GetEdmModel();

这是sample OData fork of the odata/webapi repository

选项 2

ConfigureServices 中设置 MVC JSON 选项。现在 JSON 响应将以驼峰形式出现。

services
    .AddMvc()
    .AddJsonOptions(options => {
        options.SerializerSettings.ContractResolver = 
            new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver();
    });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-18
    • 1970-01-01
    • 2021-03-05
    • 1970-01-01
    • 1970-01-01
    • 2011-07-29
    • 1970-01-01
    相关资源
    最近更新 更多