When developing I like to have strongly typed objects for certain values. An example could be a username. I’ve managed to create these value objects with validation of business rules in the constructor (the objects are immutable), but I when serializing these objects they behave funky.
[DebuggerDisplay("{Value}")]
public class Username
{
private readonly string value;
public Username(string value)
{
if (string.IsNullOrEmpty(value))
throw new ArgumentException("value", "Must have a value");
if (value.Length > 50)
throw new ArgumentOutOfRangeException("value", "Maximum length of a username is 50");
this.value = value;
}
public string Value
{
get { return value; }
}
public static implicit operator string(Username username)
{
return username.Value;
}
public static explicit operator Username(string value)
{
return new Username(value);
}
}
My question is: Using a serializer such as Newtonsoft Json.Net how go i get this value to be serialized as { Username:"foobar" }?
Never tried this but I’d guess it support type converters.
Add the TypeConverter attrib to your class and create a converter for it (from string to username and vice versa)
Newtonsoft.json.net seems to support this:
http://www.symbolsource.org/Public/Metadata/Project/Json.NET/3.5-Release-6/Release/net-3.5/Newtonsoft.Json/Newtonsoft.Json/Utilities/ConvertUtils.cs
See the portion of the code starting with
“// see if source or target types have a TypeConverter that converts …”