If you are using .NET 3.5 or later (and I hope you do), you can use JavaScriptSerializer instead. It's more "dynamic" (doesn't require [DataContract] and [DataMember] attributes) and I've never had any problems with it before.
You just pick up any object you want, any type and serialize with it :)
In .net 3.5 it was part of the System.Web.Extensions.dll, but in .NET 4 this assembly is now part of the framework.
You can easily add your own custom Serializer code to it, and handle it manually. This way you'll get the control that you want, and you'll know which property misbehaves!
e.g:
void Main()
{
var js = new JavaScriptSerializer();
js.RegisterConverters(new[] { new PonySerializer() });
var pony = js.Deserialize<Pony>(@"{""Foo"":""null""}");
pony.Dump();
}
public class PonySerializer : JavaScriptConverter
{
public override IEnumerable<Type> SupportedTypes
{
get { return new [] { typeof(Pony) }; }
}
public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
{
throw new NotImplementedException();
}
public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
{
if (dictionary == null)
throw new ArgumentNullException("dictionary");
if (type == typeof(Pony))
{
var pony = new Pony();
int intValue;
if (!int.TryParse(dictionary["Foo"] as string, out intValue))
intValue = -1; // default value. You can throw an exception or log it or do whatever you want here
pony.Foo = intValue;
return pony;
}
return null;
}
}
public class Pony
{
public int Foo { get; set; }
}
P.S. This example was written in LinqPad, hence the missing usings, parameters on Main() etc :P