zola25
zola25

Reputation: 1911

Custom JsonConverter attributes not working with Json.Serialize() using Newtonsoft.JSON in ASP.NET Core 3.1

I want to use Newtonsoft Json.NET to perform de/serialization in an ASP.NET Core 3.1 application. I've put the following in my startup ConfigureServices code:

services.AddMvc().AddNewtonsoftJson();

I've got an MVC model with custom serialization attributes:

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

In my view I serialize it to JSON:

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

But it doesn't use MyCustomJsonConverter. Breakpoints aren't hit in MyCustomJsonConverter.

An answer might be to add to the global Json settings:

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

    });

But then MyCustomJsonConverter is applied to every DateTime property rather than just the ones with the attribute applied. I could also use the JSON.Serialize overload:

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

But I don't want to do this every time I call it. I'm pretty sure these JsonConverter attributes worked fine by themselves before the switch away from Newtonsoft Json.NET in 3.0. Any ideas what I'm doing wrong?

Upvotes: 1

Views: 2215

Answers (1)

Kos
Kos

Reputation: 567

In your view add using for Newtonsoft and use its Serializer.

@using Newtonsoft.Json;

...

..(@JsonConvert.SerializeObject(Model))

The reason is not working is that you are using Serializers from different libraries one from Microsoft.AspNetCore.Mvc.Rendering and the other from Newtonsoft.Json

Upvotes: 3

Related Questions