Skip to content

ISerialize interface

wvdvegt edited this page Jan 14, 2019 · 9 revisions

The ISerialize interface as used by the ClientSideGameStorageAssetto (de)serialize values. It allows support for both XML and JSON serializer.

Below is an implementation for Json.NET from NewtonSoft. This implementation should work wherever Json.NET is supported and will support fields and properties.

On Unity3D the JsonUtility in UnityEngine.JSONSerializeModule is also an option but although it's fast and does not require an external library, it only supports fields (so no properties or classes will be serialized).

Note: The older version of this interface used a generic in the Deserialize method (Deserialize) instead of a Type parameter. This however led to issues with the il2cpp optimizer that stripped to much code.

    /// <summary>
    /// Supports the given format.
    /// </summary>
    ///
    /// <param name="format"> Describes the format to use. </param>
    ///
    /// <returns>
    /// true if it succeeds, false if it fails.
    /// </returns>
    public bool Supports(SerializingFormat format)
    {
        switch (format)
        {
            //case SerializingFormat.Binary:
            //    return false;
            case SerializingFormat.Xml:
                return false;
            case SerializingFormat.Json:
                return true;
        }

        return false;
    }

    /// <summary>
    /// Deserialize this object to the given textual representation and format.
    /// </summary>
    ///
    /// <param name="t">      A Type to process. </param>
    /// <param name="text">   The text to deserialize. </param>
    /// <param name="format"> Describes the format to use. </param>
    ///
    /// <returns>
    /// An object.
    /// </returns>
    public object Deserialize(Type t, string text, SerializingFormat format)
    {
        return JsonConvert.DeserializeObject(text, t);
    }

    /// <summary>
    /// Serialize this object to the given textual representation and format.
    /// </summary>
    ///
    /// <param name="obj">    The object to serialize. </param>
    /// <param name="format"> Describes the format to use. </param>
    ///
    /// <returns>
    /// A string.
    /// </returns>
    public string Serialize(object obj, SerializingFormat format)
    {
        return JsonConvert.SerializeObject(obj, Formatting.Indented);
    }

Clone this wiki locally