ASP.NET Core - JsonConvert.DeserializeObject不尊重CamelCasePropertyNamesContractResolver

时间:2018-03-23 06:20:53

标签: json asp.net-core json.net camelcasing

我需要将一些JSON文件输出到客户端应用程序。所以,我有以下代码

var content = System.IO.File.ReadAllText(this.path);
var model = JsonConvert.DeserializeObject(content, new JsonSerializerSettings() { 
    ContractResolver = new CamelCasePropertyNamesContractResolver() 
});

return Ok(model);

它应该以带有camelCase属性名称的Object返回,但我得到它与J​​SON文件中的相同(PascalCase)

enter image description here

要提到的,在启动文件中,IMvcBuilder.AddJsonOptions也设置了

services.AddMvc()
    .AddJsonOptions(options => {
        options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
        options.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local;
});

并且它完美地工作,其他控制器按预期返回对象。问题仅在于从JSON文件转换的对象。

我该如何解决?

1 个答案:

答案 0 :(得分:0)

好的,我找到了用

修复它的方法
<header>
  <section>
    <div class="img_content">
      <div class="bg_img" style="background-image: url(http://lorempixel.com/400/200/sports);">
        <div class="container">
          <h1 class="content_h1">Most Popular Lunches: Week 11</h1>
        </div>
      </div>
    </div>
  </section>
</header>

现在按预期工作:| enter image description here