Table of Contents

Using System.Text.Json for Serialization

The System.Text.Json serializer is .NET's latest JSON serializer, intended to be a modern, high-performance replacement for Newtonsoft Json.NET. Use the CacheBuilder.SetSerialization method to use System.Text.Json with the Scaleout.Client library.

For convenience, the CacheBuilder.UseJsonSerialization method can be instead of the approach below to set up a JSON serializer. The example provided here is equivalent and can be used as the basis for advanced custom serializer configuration.

Example

using Scaleout.Client;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;

public class Player
{
    public string PlayerId { get; set; }

    public List<int> ScoreHistory { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        var conn = GridConnection.Connect("bootstrapGateways=localhost:721");

        // Configure cache for JSON serialization:
        var builder = new CacheBuilder<int, Player>("players", conn);
        builder.SetSerialization(SerializePlayer, DeserializePlayer);

        var playerCache = builder.Build();
    }


    // Options to be used with JsonSerializer.
    private static readonly JsonSerializerOptions s_jsonSerializerOptions = 
    new JsonSerializerOptions()
    {
        PropertyNamingPolicy = JsonNamingPolicy.CamelCase
    };

    public static void SerializePlayer(Player player, Stream stream)
    {
        JsonSerializer.Serialize(stream, player, s_jsonSerializerOptions);
    }

    public static Player DeserializePlayer(Stream stream)
    {
        return JsonSerializer.Deserialize<Player>(stream, s_jsonSerializerOptions);
    }
}