System.Text.Json dictionary deserialisation issue with Refit

If you find that your Dictionary object, if it has a string key, and it is not deserialized with its first initial capitalized, and you are using System.Text.Json serializer, here is the solution.

This is only applies to some versions of the Refit NuGet package, where NewtonSoftJson is not the default serializer.

Solution using Refit

Define RefitSettings when creating your rest service, like this:

RestService.For<IAnythingApi>(
			Constans.BackendApiUrl,
			new RefitSettings
			{
				ContentSerializer = new SystemTextJsonContentSerializer(
                    new JsonSerializerOptions
					{
						DictionaryKeyPolicy = JsonNamingPolicy.CamelCase
                    }),
			});

This solution will allow you to deserialise with uppercase letter key 🙂

This content has 3 years. Some of the information in this post may be out of date or no longer work. Please, read this page keeping its age in your mind.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.