Home » C# » Serializing Complex Object for Redis

Serializing Complex Object for Redis

I have been using Redis since few weeks now and I stumble into a weird problem after few days. At first, my serialization was fine. I was able to serialize, cache and deserialize without problem. After few times, I wasn’t able to unserialize my serialize.

First of all, I am using JSON.Net for serialization and deserialization. It is the common serializer library for a long time, it’s even the one Microsoft is using now for all its new projects. Second, I was already using some configurations to handle references. The problem was that one of the object had a collection of an interface which it was not deserialized correctly because JSON.Net did not know to which concrete type to instanciate.

To fix this issue and have during serialization the concrete type added to the serialization, you need to use JsonSerializerSettings with the TypeNameHandling property to All. The result look like the following code:

var serializedObjectToCache =  JsonConvert.SerializeObject(objectToCache
                       , Formatting.Indented
                       , new JsonSerializerSettings
                       {
                           ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
                           PreserveReferencesHandling = PreserveReferencesHandling.Objects,
                           TypeNameHandling = TypeNameHandling.All
                       });

The result of the serialization is a JSON attribute named “$type” which has the complete namespace and class name. You can find more detail on JSON.Net documentation about TypeNameHandling.

The deserialization contains also the same JsonSerializerSettings.

var obj = JsonConvert.DeserializeObject<T>(serializedObject
                        , new JsonSerializerSettings
                        {
                            ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
                            PreserveReferencesHandling = PreserveReferencesHandling.Objects,
                            TypeNameHandling = TypeNameHandling.All
                        });

With the three settings used in this article, you can serialize complex object with recursive references, with abstract type or interface type and not have to worry about serializing an Entity Framework object. So, why this is not the default configuration? Because this add a lot of information in the JSON. This shouldn’t be a huge problem if you are using it with Redis, more a problem is you transfer the information through an Ajax call.

If you like my article, think to buy my annual book, professionally edited by a proofreader. directly from me or on Amazon. I also wrote a TypeScript book called Holistic TypeScript

5 Responses so far.

  1. Nice post! It will be shared in our next RedisWeekly!

  2. Itamar Haber says:

    Consider adding de/compression to your de/serialization methods for major savings of Redis’ RAM & network – there’s no point in storing clear JSON data in Redis if you’re not doing server-side processing on it #IfItsOpaqueCompressIt

  3. Sean says:

    I had a Redis implementation of my own, but ran into issues serializing EF objects. So I found this article! 😀

    But when I tried using the serializer options you have specified, I got a StackOverflowException when serializing a complex EF object. While debugging I’ve noted that the object I’m passing to JsonConvert to serialize is a System.Data.Entity.DynamicProxies subtype with my EF type being its target – which is to be expected since EF uses the dynamic proxy to enable change tracking and some other features.

    I’m gonna try to play around with it a bit more, because this article kinda leads me to believe that this code should work with any EF type. Is that not true?

Leave a Reply to Patrick Desjardins Cancel reply

Your email address will not be published. Required fields are marked *

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