Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>IMHO the best thing would be to change the <code>Foo</code> type from <a href="http://msdn.microsoft.com/en-us/library/system.int32.aspx" rel="nofollow noreferrer"><code>Int32</code></a> to <a href="http://msdn.microsoft.com/en-us/library/b3h38hb0.aspx" rel="nofollow noreferrer"><code>System.Nullable&lt;Int32&gt;</code></a> as this would best reflect its semantics (if it can be null) but if you cannot modify this class AND if using <a href="http://msdn.microsoft.com/en-us/library/system.runtime.serialization.json.datacontractjsonserializer.aspx" rel="nofollow noreferrer">DataContractJsonSerializer</a> is not an obligation for you, <a href="http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx" rel="nofollow noreferrer">Json.NET</a> has extension points that allow you to do this (it also happens to be <a href="http://james.newtonking.com/archive/2010/01/01/net-serialization-performance-comparison.aspx" rel="nofollow noreferrer">better performing</a>).</p> <p>For example you could write a custom type converter:</p> <pre><code>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(); } } </code></pre> <p>that could be registered and used like this:</p> <pre><code>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&lt;Pony&gt;(jsonReader); Console.WriteLine(pony.Foo); } } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload