JSON在PascalCase中返回属性

JSON在PascalCase中返回属性

本文介绍了JSON在PascalCase中返回属性,而不是camelCase的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Microsoft.AspNetCOre.OData 7.0.1,如果我有一个不在数据库中的Models列表,则JSON结果总是以PascalCase而不是camelCase的形式返回.如何获得我的清单为camelCase?

Using Microsoft.AspNetCOre.OData 7.0.1, if I have a list of Models that are NOT in the database, the JSON result always comes back as PascalCase instead of camelCase. How can I get my list to be camelCase?

下面的相对示例:

我的模型不在数据库中.

My model that is NOT in the database.

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以以下格式返回

/api/GetWidgets?$select=name returns in the following format

{ Name: "Widget" }

推荐答案

选项1

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

Option 1

Even though Widget is not in the database, you can add it to the Entity Data Model (EDM). The EDM probably has camel case as its convention. Widget will pick up that convention.

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

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

_edmModel = builder.GetEdmModel();

这是 odata/webapi存储库的示例OData分支.

ConfigureServices中设置MVC JSON选项.现在,JSON响应将采用驼峰格式.

Set the MVC JSON options in ConfigureServices. Now JSON responses will be in camel case.

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

这篇关于JSON在PascalCase中返回属性,而不是camelCase的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 07:32