Table of Contents

Using Json.NET for Serialization

Newtonsoft Json.NET can be used to serialize objects stored in the ScaleOut service. Use the CacheBuilder.SetSerialization method to use Json.NET with the Scaleout.Client library.

Example

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Newtonsoft.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();
    }


    private static readonly UTF8Encoding UTF8NoBom = new UTF8Encoding(
            encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);

    public static void SerializePlayer(Player player, Stream stream)
    {
        var serializer = new JsonSerializer();

        // The Scaleout.Client library will close the supplied 
        // stream for us later, so don't let the StreamWriter
        // close it here it during disposal.
        using (var sw = new StreamWriter(stream,
                                         UTF8NoBom,
                                         bufferSize: 1024,
                                         leaveOpen: true))
        using (var writer = new JsonTextWriter(sw))
        {
            serializer.Serialize(writer, player);
            writer.Flush();
        };

    }

    public static Player DeserializePlayer(Stream stream)
    {
        var serializer = new JsonSerializer();

        // The Scaleout.Client library will close the supplied 
        // stream for us later, so don't let the StreamReader
        // close it here it during disposal.
        using (var sr = new StreamReader(stream,
                                         Encoding.UTF8,
                                         detectEncodingFromByteOrderMarks: false,
                                         bufferSize: 1024,
                                         leaveOpen: true))
        using (var jsonTextReader = new JsonTextReader(sr))
        {
            return serializer.Deserialize<Player>(jsonTextReader);
        }
    }
}