ASP.NET Core 3.1: Newtonsoft.Json Issues With Enumerable.Empty<T> Assignment

Written by Ken Dale

We’ve spotted some strange behavior before with ASP.NET Core and JSON serialization/deserialization, and I eventually made it back to trying out some scenarios.

One thing we’ve noticed is Newtonsoft.Json having issues with Enumerable.Empty<T>() assignments. We typically assign IEnumerable<T> items with a starting (empty, itemless) collection to avoid a potential null.

When ran directly it throws a JsonSerializationException. When ran through TestServer it returns a 400 Bad Request.

A fix

A fix, as mentioned by Bill Boga and demonstrated via tests (see https://github.com/kendaleiv/AspNetCoreJsonTests/commit/8a538f8a6d8d32b68c4eb331dddee9792ada8372), is to install the Newtonsoft.Json package manually, even if it’s not absolutely necessary for the project to compile.

Workaround

We can change all usages of Enumerable.Empty<T>() to something else, like new List<T>(), Array.Empty<T>(), etc. This makes everything just work the way you’d expect.

In Closing

Tests associated with this post are at:

Published June 05, 2020 by

undefined avatar
Ken Dale Senior Application Developer (Former)

Suggested Reading