【问题标题】:ASP.NET Core MVC dynamic return is not camelCasedASP.NET Core MVC 动态返回不是驼峰式
【发布时间】:2018-01-18 12:59:02
【问题描述】:

从您的服务返回一个强类型对象,并将 JSON 属性呈现为驼峰式,因为这是 ASP.NET Core MVC 中的默认设置。

但是,有时我们需要使用 dynamic 关键字和 ExpandoObject 类即时创建一些东西。

那些属性不再是驼峰式了。

如何强制 ASP.NET Core MVC to comeCase 一切?

【问题讨论】:

    标签: c# asp.net-core camelcasing


    【解决方案1】:

    在您的 Startup.cs 中,您可以指定用于序列化的解析器。您正在寻找的是 CamelCasePropertyNamesContractResolver,它可以通过以下方式启用:

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

    我已经用动态类型对其进行了测试,它按预期工作。

    【讨论】:

    • 我已经使用 ASP.NET Core 2.2 进行了尝试,但没有成功,我仍然看到类型化对象中的动态对象是 (Upper)PascalCase 而不是 camelCase,而类型化对象属性确实是骆驼案...
    【解决方案2】:

    我最近一直在尝试使用System.Text.JsonExpandoObject 序列化为camelCase,但运气不佳。但是,我确实设法使用Newtonsoft.Json 实现了这一点。

    对于那些可能正在寻找单元级或非 MVC 解决方案而不是像我这样建议的配置级解决方案的人,这里是我的发现。

    dynamic d = new ExpandoObject();
    d.Foo = new ExpandoObject();
    d.Foo.BarBaz = null;
    

    System.Text.JsonJsonSerializerOptions 一起使用,属性名称被序列化,但是,在目前序列化过程中,camelCasePropertyNamingPolicy 的值似乎被忽略(在撰写本文时在.NET 5 上进行了测试)。但是,它确实会继续序列化对象而不会失败或异常。

    var options = new JsonSerializerOptions
    {
        PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
    };
    
    string json = JsonSerializer.Serialize<ExpandoObject>(d, options);
    Console.WriteLine(json);
    

    这会输出

    {"Foo":{"BarBaz":null}}

    我能够使用之前建议的CamelCasePropertyNamesContractResolver 作为ContractResolver 的实例来实现预期的效果,以用于传递给SerializeObject 方法的JsonSerialierSettings 实例。

    var settings = new JsonSerializerSettings 
    { 
        ContractResolver = new CamelCasePropertyNamesContractResolver() 
    };
    
    string output = JsonConvert.SerializeObject(d, settings);
    Console.WriteLine(output);
    

    输出是……

    {"foo":{"barBaz":null}}

    【讨论】:

      【解决方案3】:

      在 .NET 5 上,需要配置一个特定的标志来序列化字典键

      services.AddControllers()
                      .AddJsonOptions(o =>
                          o.JsonSerializerOptions.DictionaryKeyPolicy = System.Text.Json.JsonNamingPolicy.CamelCase
                      );
      

      更多信息
      JsonSerializerOptions.DictionaryKeyPolicy Property
      GitHub Issue

      【讨论】:

        猜你喜欢
        • 2013-05-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-22
        • 1970-01-01
        • 2020-10-12
        • 1970-01-01
        相关资源
        最近更新 更多