JsonConvert.DeserializeObject problem with complex types

Mar 22, 2010 at 3:10 PM

Hi.

I'm trying to serialize / deserialize an object with complex types, but I can't understand how this is supposed to be done.

My class looks something like this:

internal class TestClass 
{
       public virtual Guid Id { get; set; }
       public virtual int? Year { get; set; }
       public virtual string Company { get; set; }
       public virtual IRange<DateTime> DateRange { get; set; }
       public virtual IRange<decimal> DecimalRange { get; set; }
}

My problem is with the interfaces. I tried using a CustomCreationConverter that creates a instance of the desired class. The problem is that my program allows one of the ranges to be null, and if one of the ranges in the serialized object is null I get this error: "Unexpected initial token 'Null' when populating object. Expected JSON object or array." I thought this could be handled with the NullValueHandling.Ignore, but am I able to set JsonConverters and JsonSerializerSettings at the same time using JsonConvert.DeserializeObject<TestClass>(...) ? Am I missing something here, or is this by design? 

Thanks.
Magne

 

Coordinator
Mar 23, 2010 at 2:16 AM

No that is a bug which I've now fixed. If DecimalRange has a null value in JSON it will now be set as a null value on your class.

http://json.codeplex.com/SourceControl/list/changesets

 

Mar 23, 2010 at 9:22 AM
Edited Mar 23, 2010 at 12:59 PM

Thank you sir! :)

But now it looks like all the complex types is set to a default value in the deserialized object.

If the json string includes null for one range, the deserialized object does not have null for the range, but haves a default instance of the range.

Edit: I am also having problem with nullable enums, it is null in the json string, but in the deserialized object it gets the value 0(also with nullable int?)..

Thanks
Magne

Mar 30, 2010 at 7:53 AM

Sorry, my mistake. I had private setters on some properties.

Everything works now.

Thanks for a great product!

Magne