using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;
namespace ConsoleApplication1 {
internal class Program {
private static void Main(string[] args) {
var pony = new Pony();
var serializer = new DataContractJsonSerializer(pony.GetType());
var example = @"{""Foo"":null}";
var stream = new MemoryStream(Encoding.UTF8.GetBytes(example.ToCharArray()));
stream.Position = 0;
pony = (Pony) serializer.ReadObject(stream);
// The previous line throws an exception.
}
}
[DataContract]
public class Pony {
[DataMember]
private int Foo { get; set; }
}
}
Sometimes the serialization throws a casting error on Int32s being set to null. Is there any way to hook into the Json-serializer?
IMHO the best thing would be to change the Foo type from Int32 to System.Nullable<Int32> as this would best reflect its semantics (if it can be null) but if you cannot modify this class AND if using DataContractJsonSerializer is not an obligation for you, Json.NET has extension points that allow you to do this (it also happens to be better performing).
For example you could write a custom type converter:
internal class NullableIntConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(int);
}
public override object ReadJson(JsonReader reader, Type objectType, JsonSerializer serializer)
{
if (reader.Value == null)
{
return default(int);
}
return int.Parse(reader.Value.ToString());
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new System.NotImplementedException();
}
}
that could be registered and used like this:
internal class Program
{
private static void Main(string[] args)
{
var serializer = new JsonSerializer();
serializer.Converters.Add(new NullableIntConverter());
using (var reader = new StringReader(@"{""Foo"":null}"))
using (var jsonReader = new JsonTextReader(reader))
{
var pony = serializer.Deserialize<Pony>(jsonReader);
Console.WriteLine(pony.Foo);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With