Contribute to Docs Contribute to Docs


By default, all field values are stored as JSON. Although this is very flexible it's not always the best when trying the get your data indexed and searchable in good way. Serializers give you the option to specify how data should saved & loaded from the database for your custom fields.

The ISerializer Interface

To create a serializer you must implement the ISerializer interface from the Piranha.Extend namespace.

string Serialize(object obj)

This method serializes the field value to a string that can be stored in the database.

object Deserialize(string str)

This method deserializes the given string into the object type of the field value.

An Example

As an example lets look at the serializer for the standard ImageField. This serializer only stores the actual Id of the referenced image in the database as its value.

using Piranha.Extend;
using Piranha.Extend.Fields;

public class ImageFieldSerializer : ISerializer
    public string Serialize(object obj)
        if (obj is ImageField)
            return ((ImageField)obj).Id.ToString();
        throw new ArgumentException();

    public object Deserialize(string str)
        return new ImageField
            Id = !string.IsNullOrEmpty(str) ? new Guid(str) : (Guid?)null

Registering a Serializer

You register your custom serializers in the application startup. The core serializers are registered when calling Piranha.App.Init(). This is how the ImageSerializer is registered.

Piranha.App.Serializers.Register<ImageField>(new ImageFieldSerializer());

This basically lets Piranha know that when an ImageField is loaded from, or saved to the database, the specified serializer should be used. As you can see, all serializers are singletons and should not contain any state or instance information.