Computer Beacon high quality .NET libraries in open source

Custom types in serialization

The SerializeObject and DeserializeObject methods are called recursively in the Serializer class. To handle custom types, override these methods. You should call the base class implementation if the type is already supported.

Example: supporting DateTime values

class CustomSerializer : ComputerBeacon.Json.Serializer {
    public override void SerializeObject(StringBuilder sb, object o) {
        if (o.GetType() == typeof(DateTime)) SerializeObject(sb, ((DateTime)o).ToString());
        else base.SerializeObject(sb, o);
    }
    public override object DeserializeObject(Type targetType, object jsonValue) {
        if (targetType == typeof(DateTime) && jsonValue.GetType() == typeof(string)) return Convert.ToDateTime(jsonValue as string);
        return base.DeserializeObject(targetType, jsonValue);
    }
}

Using the customized serializer

User u = new User() {...};

var serializer = new CustomSerializer(); //this may be cached to a static field for improved performance
string s = Serializer.Serialize(u, serializer);

u2 = Serializer.Deserialize(typeof(User), s, serializer);