Custom DatafieldSerializers

You can write your own DatafieldSerializers when specific serializationrules are required for a Datafield.

Creating custom DatafieldSerializers

For the DatarecordSerializer to be able to use a custom DatafieldSerializer, the custom DatafieldSerializer must inherit from DatafieldSerializer<T>. Where T is the type of DatafieldAttribute.

Example:

    public class BooleanSerializer : DatafieldSerializer<PositionBasedDatafieldAttribute>
{
public override Type DatafieldType
{
get { return typeof(bool); }
}

public override string Serialize(object datafield, PositionBasedDatafieldAttribute datafieldAttribute)
{
var value = (bool)datafield;

switch (datafieldAttribute.Format)
{
case "YN":
case "yn":
case "Y":
case "y":
return value ? "Y" : "N";
case "JN":
case "jn":
case "J":
case "j":
return value ? "J" : "N";
case "01":
case "1":
return value ? "1" : "0";
default:
return value.ToString(CultureInfo.CurrentCulture);
}
}

public override object Deserialize(string datafield, PositionBasedDatafieldAttribute datafieldAttribute)
{
switch (datafieldAttribute.Format)
{
case "YN":
case "yn":
case "Y":
case "y":
return datafield.ToLower() == "y" ? true : false;
case "JN":
case "jn":
case "J":
case "j":
return datafield.ToLower() == "j" ? true : false;
case "01":
case "1":
return datafield.ToLower() == "1" ? true : false;
default:
{
bool result;
if (bool.TryParse(datafield, out result))
{
return result;
}

throw new DatafieldSerializationException();
}
}
}
}

Using custom DatafieldSerializers

The BooleanSerializer in the example can now be used on a Datarecord as follows:

    [PositionBasedDatarecord(1)]
class PositionBasedTestDatarecordWithBooleanSerializer
{
[PositionBasedDatafield(0, 1, Format = "Y", SerializerType = typeof(BooleanSerializer))]
public bool Field { get; set; }
}

When an instance of the record is created with the value of the Field property set to true, the serialized value of the record will be "Y":

            var record = new PositionBasedTestDatarecordWithBooleanSerializer { Field = true };

var serializer = new DatarecordSerializer<PositionBasedTestDatarecordWithBooleanSerializer>();
var result = serializer.Serialize(record);

When an instance of the record is created with the value of the Field property set to false, the serialized value of the record will be "N":

            var record = new PositionBasedTestDatarecordWithBooleanSerializer { Field = false };

var serializer = new DatarecordSerializer<PositionBasedTestDatarecordWithBooleanSerializer>();
var result = serializer.Serialize(record);

And vice-versa, deserialization of "Y" will result in an instance of the record with the value of Field set to true:

            var serializer = new DatarecordSerializer<PositionBasedTestDatarecordWithBooleanSerializer>();
var result = serializer.Deserialize("Y");

Last edited Oct 2, 2012 at 10:35 PM by Coilz, version 7

Comments

No comments yet.