【问题标题】:Custom JsonConverter attributes not working with Json.Serialize() using Newtonsoft.JSON in ASP.NET Core 3.1在 ASP.NET Core 3.1 中使用 Newtonsoft.JSON 的自定义 JsonConverter 属性不适用于 Json.Serialize()
【发布时间】:2020-04-08 02:41:43
【问题描述】:

我想使用 Newtonsoft Json.NET 在 ASP.NET Core 3.1 应用程序中执行反序列化。我在启动 ConfigureServices 代码中添加了以下内容:

services.AddMvc().AddNewtonsoftJson();

我有一个带有自定义序列化属性的 MVC 模型:

public class MyModel {
    [Newtonsoft.Json.JsonConverter(typeof(MyCustomJsonConverter))]
    public DateTime MyProperty {get; set;}
}

在我看来,我将其序列化为 JSON:

<script>
    someJsFunction(@Json.Serialize(Model));
</script>

但它不使用 MyCustomJsonConverter。 MyCustomJsonConverter 中没有命中断点。

答案可能是添加到全局 Json 设置中:

services.AddMvc().AddNewtonsoftJson(options =>
    {
        options.SerializerSettings.Converters = new List<JsonConverter>()
        {
            new MyCustomJsonConverter()
        };

    });

但是 MyCustomJsonConverter 会应用于每个 DateTime 属性,而不仅仅是应用了该属性的那些。我也可以使用 JSON.Serialize 重载:

<script>
    someJsFunction(@Json.Serialize(Model, new JsonSerializerSettings()
                                           {
                                               Converters = new List<JsonConverter> { new MyCustomJsonConverter()},       
                                           }
                                  ));
</script>

但我不想每次调用它时都这样做。我很确定这些 JsonConverter 属性在 3.0 中从 Newtonsoft Json.NET 切换之前可以正常工作。任何想法我做错了什么?

【问题讨论】:

    标签: c# json asp.net-core json.net asp.net-core-3.0


    【解决方案1】:

    在您看来,为 Newtonsoft 添加 using 并使用其序列化器。

    @using Newtonsoft.Json;
    
    ...
    
    ..(@JsonConvert.SerializeObject(Model))
    

    无法正常工作的原因是您使用来自不同库的序列化程序,一个来自Microsoft.AspNetCore.Mvc.Rendering,另一个来自Newtonsoft.Json

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-22
      • 1970-01-01
      • 1970-01-01
      • 2019-08-02
      • 2017-12-05
      • 2017-03-31
      • 1970-01-01
      • 2021-02-01
      相关资源
      最近更新 更多