This project has moved and is read-only. For the latest updates, please go here.

LINQ to JSON: Reading optional value as nullable.

Nov 21, 2008 at 11:22 PM
Edited Nov 21, 2008 at 11:22 PM
I'm attempting to use LINQ to JSON (Json.NET 3.5 beta 1) to read an object property that may or may not be present, but if it is present, it's a boolean value. I had thought to use a nullable boolean to do so:

bool? foo = myJObject.Value<bool?>("foo");

This works just fine if "foo" is not present on the object, but if it is present, I get the following error. Am I doing something wrong? If so, what would be the preferred way to accomplish this?

Invalid cast from 'System.Boolean' to 'System.Nullable`1[[System.Boolean, mscorlib, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'.
   at System.Convert.DefaultToType(IConvertible value, Type targetType, IFormatProvider provider)
   at System.Boolean.System.IConvertible.ToType(Type type, IFormatProvider provider)
   at System.Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider)
   at Newtonsoft.Json.Linq.Extensions.Convert[T,U](T token, Boolean cast) in d:\Newtonsoft\Projects\Json\trunk\Src\Newtonsoft.Json\Linq\Extensions.cs:line 267

Nov 21, 2008 at 11:36 PM
Never mind, it seems that this works. Pity the strongly-typed generic version doesn't.

bool? foo = (bool?)myJObject["foo"];
Nov 23, 2008 at 5:16 AM
I have updated and checked in the source code so that the strongly typed version works.
Nov 24, 2008 at 4:55 PM
Excellent, thank you!