Skip to content

Serialization and Deserialization With ISerializationAdapter

Christian Findlay edited this page Feb 7, 2020 · 12 revisions

Clients achieve serialization and deserialization with implementations of ISerializationAdapter. It means that RestClient.Net does not depend on any external serialization libraries. RestClient.Net can use any serialization. The aim is to follow the dependency injection pattern and not force developers to download libraries that they don't need.

JSON Serialization

Newtonsoft

RestClient.Net does not come with the most popular JSON library Newtonsoft.Json by default. Developers can add JSON support with Newtsonsoft by adding the Newtsonsoft NuGet package and copying the code for the adapter into the project.

public class NewtonsoftSerializationAdapter : ISerializationAdapter
{
    #region Implementation
    public TResponseBody Deserialize<TResponseBody>(byte[] data, IHeadersCollection responseHeaders)
    {
        var markup = Encoding.UTF8.GetString(data);
        object markupAsObject = markup;

        if (typeof(TResponseBody) == typeof(string))
        {
            return (TResponseBody)markupAsObject;
        }

        return JsonConvert.DeserializeObject<TResponseBody>(markup);
    }

    public byte[] Serialize<TRequestBody>(TRequestBody value, IHeadersCollection requestHeaders)
    {
        var json = JsonConvert.SerializeObject(value);
        var binary = Encoding.UTF8.GetBytes(json);
        return binary;
    }
    #endregion
}

Usage

var client = new Client(new NewtonsoftSerializationAdapter(), new Uri("https://restcountries.eu/rest/v2/"));
var response = await client.GetAsync<List<RestCountry>>();

Default JSON Serialization Adapter

RestClient 3.1.1 on .NET Core 3.0 introduces the default serialization method which uses System.Text.Json. This library comes packaged with .NET Core but doesn't exist on other platforms. Over time, this will most likely become the recommended serialization adapter, but there are some differences between this library and Newtsonsoft so it remains slightly experimental until it is accepted as a replacement for Newtsonsoft by the community.

This is an example. Notice that it does not require a serialization adapter as part of the constructor.

public async Task GetDefaultSerializationRestCountries()
{
    var baseUri = new Uri("https://restcountries.eu/rest/v2/");
    var client = new Client(baseUri);
    var countries = await client.GetAsync<List<RestCountry>>();
}

This serialization adapter is also recommended if the backend is an ASP Web API because System.Text.Json is compatible. Note that by default, this adapter uses case insensitive JSON properties. But, using the case-sensitive option will yield better performance.

Other Serialization

Protobuf is a recommended serialization method. Please read this article about Protobuf serialization.

Clone this wiki locally