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 2 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.

.NET JSON Serialization and deserialization flavoured with some inheritance

Imagine, you have a base class.

    public class BaseClass
    {
        public string BaseProperty { get; set; }
    }

It can have a base property in it. To keep OOP principles in mind, you are creating a derived class by of it called “InheritedClass”

    public class InheritedClass : BaseClass
    {
        public string PlusProperty { get; set; }
    }

And you are defining a container class, which holds an instance of a BaseClass or an InheritedClass. You are defining a property with BaseClass type. It will fit to InheritedClass too.

    public class ContainerClass
    {
        public BaseClass Property { get; set; }
    }

If you are casting your object, the PlusProperty’s value never gets lost, because the framework allocates the memory for an InheritedClass.

But what about, if you are serialize this object, and then deserialize it back? What do you think, what will be the result of this program?

    class Program
    {
        static void Main(string[] args)
        {
            var toBeSerialized = new ContainerClass();
            toBeSerialized.Property = new InheritedClass()
            {
                BaseProperty = "I am base property",
                PlusProperty = "I am an inherited plus property"
            };

            string serializedJSON = JsonConvert.SerializeObject(toBeSerialized);

            ContainerClass deserialized = (ContainerClass)JsonConvert.DeserializeObject(serializedJSON, typeof(ContainerClass));

            Console.WriteLine(deserialized.Property.GetType().AssemblyQualifiedName);
            Console.WriteLine((deserialized.Property as InheritedClass)?.PlusProperty);
            Console.ReadLine();
        }
    }

This code snippet gives the following result:

TestConsoleApp.BaseClass, TestConsoleApp, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null


That is because JSON does not include type names when serializing and deserializing an object.

You can set TypeNameHandling = All for your JsonSerializerSettings, but it is highly unrecommended by Microsoft, because it can lead you into security issues, allows attackers remote code execution.

        static void Main(string[] args)
        {
            var toBeSerialized = new ContainerClass();
            toBeSerialized.Property = new InheritedClass()
            {
                BaseProperty = "I am base property",
                PlusProperty = "I am an inherited plus property"
            };

            string serializedJSON = JsonConvert.SerializeObject(toBeSerialized, new JsonSerializerSettings()
            {
                TypeNameHandling = TypeNameHandling.All
            });

            ContainerClass deserialized = (ContainerClass)JsonConvert.DeserializeObject(serializedJSON, typeof(ContainerClass), new JsonSerializerSettings()
            {
                TypeNameHandling = TypeNameHandling.All
            });

            Console.WriteLine(deserialized.Property.GetType().AssemblyQualifiedName);
            Console.WriteLine((deserialized.Property as InheritedClass)?.PlusProperty);
            Console.ReadLine();
        }

Output:

TestConsoleApp.InheritedClass, TestConsoleApp, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
I am an inherited plus property

” Insecure deserializers are vulnerable when deserializing untrusted data. An attacker could modify the serialized data to include unexpected types to inject objects with malicious side effects. An attack against an insecure deserializer could, for example, execute commands on the underlying operating system, communicate over the network, or delete files. ” More details at: https://docs.microsoft.com/en-us/dotnet/fundamentals/code-analysis/quality-rules/ca2326

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.

.NET Core: Type serialization denied

When trying to return with a complex object in .NET Core API, which has a Type property in it, the serializer gives the following exception :

System.NotSupportedException: Serialization and deserialization of 'System.Type' instances are not supported and should be avoided since they can lead to security issues.

Passing Type, DataSet, DataTable through the JSON or XML serializer gives possibility to remote code execution for attackers. More information available at https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/dataset-datatable-dataview/security-guidance

Workaround:
Declare an enumeration for your types (ex: enum { string, int, etc }) you can parse the value for the requested type explicitly.

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.