Custom serialization of value types

Jan 24, 2012 at 3:39 PM

How should I handle the case where I have a value-type and want to control the serialization and deserialization whenever it is used in a object-hierarchy?

Below is an example. When serialized, the Json string should look like:

{"Content1": "My content", "Name": "My Name"}

Hence "Content2" which has no value should be null and not included.

E.g

var s = new Foo();
s.Content1 = "My content";
s.Name = "My name";

var json = Serialize(s);
var item = Deserialize(json);

[Serializable]
public class Foo
{
	public string Name { get; set; }

	public Text Content1 { get; set; }

	public Text Content2 { get; set; }
}

[Serializable]
public struct Text
{
	private readonly string _value;

	public Text(string value)
	{
		_value = value;
	}

	public static implicit operator Text(string value)
	{
		return new Text(value);
	}

	public static implicit operator string (Text item)
	{
		return item._value;
	}

	public override string ToString()
	{
		return _value;
	}
}

Jan 24, 2012 at 3:56 PM

Guess I can answer my self and at the same time ask for confirmation that I have done it right.

 

public class TextConverter : JsonConverter
{
	public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
	{
		var text = (string)(Text)value;
		writer.WriteValue(text);
	}

	public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
	{
		if(reader.TokenType != JsonToken.String)
			return new Text();

		return new Text(reader.Value.ToString());
	}

	public override bool CanConvert(Type objectType)
	{
		return objectType == typeof(Text);
	}
}