【问题标题】:ASP.NET Core - JsonConvert.DeserializeObject does not respect CamelCasePropertyNamesContractResolverASP.NET Core - JsonConvert.DeserializeObject 不尊重 CamelCasePropertyNamesContractResolver
【发布时间】:2018-03-23 06:20:53
【问题描述】:

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

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

return Ok(model);

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

需要提一下,在Startup文件中,IMvcBuilder.AddJsonOptions也设置了

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

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

我该如何解决这个问题?

【问题讨论】:

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


    【解决方案1】:

    好的,我找到了解决方法

    var model = JsonConvert.DeserializeObject<JObject>(content);
    

    现在它按预期工作了:|

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-21
      • 1970-01-01
      相关资源
      最近更新 更多