Fork me on GitHub

Serializing with Jil Edit on GitHub


Marten has also been tested using the Jil library for JSON serialization. While Jil is not as flexible as Newtonsoft.Json and might be missing support for some scenarios you may encounter, it is very clearly faster than Newtonsoft.Json.

To use Jil inside of Marten, add a class to your system like this one that implements the ISerializer interface:


public class JilSerializer : ISerializer
{
    private readonly Options _options
        = new Options(dateFormat: DateTimeFormat.ISO8601, includeInherited:true);

    public void ToJson(object document, TextWriter writer)
    {
        JSON.Serialize(document, writer, _options);
    }

    public string ToJson(object document)
    {
        return JSON.Serialize(document, _options);
    }

    public T FromJson<T>(TextReader reader)
    {
        return JSON.Deserialize<T>(reader, _options);
    }

    public object FromJson(Type type, TextReader reader)
    {
        return JSON.Deserialize(reader, type, _options);
    }

    public string ToCleanJson(object document)
    {
        return ToJson(document);
    }

    public EnumStorage EnumStorage => EnumStorage.AsString;
    public Casing Casing => Casing.Default;
    public CollectionStorage CollectionStorage => CollectionStorage.Default;
    public NonPublicMembersStorage NonPublicMembersStorage => NonPublicMembersStorage.Default;
}

Next, replace the default ISerializer when you bootstrap your DocumentStore as in this example below:


var store = DocumentStore.For(_ =>
{
    _.Connection("the connection string");

    // Replace the ISerializer w/ the TestsSerializer
    _.Serializer<TestsSerializer>();
});

See Optimizing for Performance in Marten and Optimizing Marten Part 2 for some performance comparisons of using Jil versus Newtonsoft.Json for serialization within Marten operations.