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.
Example
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using Scaleout.Client;
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)
{
var jsonWriter = new Utf8JsonWriter(stream);
JsonSerializer.Serialize(jsonWriter, player, s_jsonSerializerOptions);
jsonWriter.Flush();
}
public static Player DeserializePlayer(Stream stream)
{
// As of .NET 5, the Utf8JsonReader does not offer a way to
// deserialize from a stream. Read the supplied stream into
// a buffer until this is supported.
byte[] jsonBytes = new byte[stream.Length];
stream.Read(jsonBytes, 0, jsonBytes.Length);
Utf8JsonReader reader = new Utf8JsonReader(jsonBytes,
isFinalBlock: true,
state: default);
return JsonSerializer.Deserialize<Player>(ref reader, s_jsonSerializerOptions);
}
}