Serializing Enums and Flags

What options do I have when serializing enum values and flags?

You can serialize your enum values as strings or as numbers. In both cases you have to use a value converter.
There are 2 pre-defined value converters for serializing enums(flags). If you prefer strings, the one you need is EnumStringValueConverter, otherwise you should use EnumNumberValueConverter. They both work for enums and flags.

How does it work for enums?

Imagine you have this enum:

public enum Seasons
{
	Spring = 1,
	Summer,
	Autumn,
	Winter
}

Then with EnumStringValueConverter this is what you will get:

class WithEnumPropertyAsString : IXPathSerializable
{
	[MappingXPath("/Seasons/Season")]
	[ValueConvertor(typeof(EnumStringValueConverter))]
	public Seasons Season { get; set; }
}

var serializable = new WithEnumPropertyAsString()
{
	Season = Seasons.Summer
};

var xml = serializable.ToXml();

<Seasons>
  <Season>Summer</Season>
</Seasons>

And with EnumNumberValueConverter the result will be:

class WithEnumPropertyAsNumber : IXPathSerializable
{
	[MappingXPath("/Seasons/Season")]
	[ValueConvertor(typeof(EnumNumberValueConverter))]
	public Seasons Season { get; set; }
}

var serializable = new WithEnumPropertyAsNumber()
{
	Season = Seasons.Summer
};

var xml = serializable.ToXml();

<Seasons>
  <Season>2</Season>
</Seasons>

How does it work for flags?

Very similarly, for the flags, for example:

[Flags]
public enum PhoneFeatures
{
	TouchScreen = 1,
	Camera = 2,
	GPRS = 4,
	Wifi = 8
}

With EnumStringValueConverter you will get:

class WithFlagsPropertyAsString : IXPathSerializable
{
	[MappingXPath("/Phone/Features")]
	[ValueConvertor(typeof(EnumStringValueConverter))]
	public PhoneFeatures Features { get; set; }
}

var serializable = new WithFlagsPropertyAsString()
{
	Features = PhoneFeatures.GPRS | PhoneFeatures.TouchScreen
};

var xml = serializable.ToXml();

<Phone>
  <Features>TouchScreen, GPRS</Features>
</Phone>

And with EnumNumberValueConverter:

class WithFlagsPropertyAsNumber : IXPathSerializable
{
	[MappingXPath("/Phone/Features")]
	[ValueConvertor(typeof(EnumNumberValueConverter))]
	public PhoneFeatures Features { get; set; }
}

var serializable = new WithFlagsPropertyAsNumber()
{
	Features = PhoneFeatures.GPRS | PhoneFeatures.TouchScreen
};

var xml = serializable.ToXml();

<Phone>
  <Features>5</Features>
</Phone>

Read next: Serializing Arrays

.

Last edited Nov 10, 2012 at 2:16 PM by artemkv, version 4

Comments

No comments yet.