JSON serialization in Redis cache

Hi,

having an object declared like this

public class CacheEntry
{
public DateTime CreatedOn { get; set; }

public string CacheKey { get; set; }

public object CachedObject { get; set; }

}

It is serialized in redis using :
_cacheClient.Set(cacheKey,value,new TimeSpan(0,0, expiresInSeconds));

In redis it stored like that :

{
“CreatedOn”: “2016-09-12T08:22:37.8215667Z”,
“CacheKey”: “GetCompetitionTypes”,
“CachedObject”: [
{
"__type": “SDR.DataModel.Competition.Raw.CompetitionType, SDR.DataModel”,
“ID”: -3,
“Code”: “EURO”,
“Name”: “European Championship”,
“ShortName”: “EURO”,
“ActiveSeason”: 2016,
“IsTeamCompetition”: true,
“Competitions”: [],
“Languages”: [],
“DataCoverage”: “All”,
“LiveSource”: “CDWS”,
“StatsSource”: “CDWS”
},
{
“ID”: 3,
“Code”: “EURO”,
“Name”: “European Championship”,
“ShortName”: “EURO”,
“ActiveSeason”: 2016,
“IsTeamCompetition”: true,
“Competitions”: [],
“Languages”: [],
“DataCoverage”: “All”,
“LiveSource”: “CDWS”,
“StatsSource”: “CDWS”
}, … etc …

When I tr to get it back
return _cacheClient.Get(cacheKey);

the CachedObject property is a plain string containing what has been stored in redis … seems the __type hint on (only) the first item of the list is not “enough” to deserialize the object back in the proper way.

What could be the problem ?
thank you
enrico

The serializer can’t tell from the object data type what it should be deserialized back to. When it goes to deserialize it only see’s object and since it’s not an object with a __type hint it leaves it untouched as a string (which is an object). Note: use of object is highly discouraged for runtime issues like this.

It should work if you wrap the collection into a containing object or even better get rid of the CacheEntry wrapper and let the call-site dictate what the Response Type should be serialized into, e.g:

List<CompetitionType> results = ...;
cache.Set(cacheKey, results, expiresIn);
var fromCache = cache.Get<List<CompetitionType>>(cacheKey);

Why are you serializing values in a cache entry wrapper on top of Redis which is a dedicated Cache? Seems highly inefficient and unnecessary.

hi, thank you for the response …
I turned the CachedObject property into as string and serialized and deserialized it explicitly before / after I get / put the CacheEntry into redis via icacheclient (since when deserializing I actually know the type I have to deserialize into) …

I defined a CacheEntry class to add some info on the cached entry (ttl and key ) only for debugging pourpose. I could acually safely remove this class.

thank you