0Pricing
C# Academy · Lesson

Caching Serialized Objects

Store and retrieve complex objects.

Caching More Than Strings

Real apps cache objects, not just strings. Since IDistributedCache stores bytes, you must serialize your object to a byte/string representation, and deserialize on the way out. JSON is the usual choice.

Serializing With System.Text.Json

Use System.Text.Json to turn an object into a JSON string, then store it with SetStringAsync.

using System.Text.Json;

var product = new Product { Id = 1, Name = "Coffee", Price = 4.5m };
string json = JsonSerializer.Serialize(product);
await _cache.SetStringAsync("product:1", json);

All lessons in this course

  1. IDistributedCache Abstraction
  2. Connecting to Redis
  3. Cache Patterns and Expiration
  4. Caching Serialized Objects
← Back to C# Academy