Search code examples
c#jsonjavascriptserializerargumentnullexception

JavaScriptSerializer throwing ArgumentNullException on deserialization


I'm writing an application that posts and gets JSON to/from a backend in Visual C# 4.0.

Obviously, the easiest way to serialize/deserialize the JSON is System.Web.Script.Serialization.JavaScriptSerializer, but I'm having a weird error where it's throwing a ArgumentNullException, claiming that type is null.

When the following JSON is deserialized, it works fine:

 {"results":[
      {"Name":"Western Bulldogs",
      "updatedAt":"2011-08-22T09:09:09.673Z",
      "Nickname":"Bulldogs",
      "RemoteId":44,
      "Abbreviation":"WB",
      "createdAt":"2011-08-22T09:09:09.673Z",
      "objectId":"2iSK8FDTA6"}
 ]}

However, when deserializing the second one (with the nested dictionary), it fails with the type is null error.

{"results":[
    {"EndDate":{"iso":"2011-09-06T00:00:00.000Z","__type":"Date"},
    "Name":"Round 24",
    "updatedAt":"2011-08-22T08:33:54.119Z",
    "RemoteId":800,"createdAt":"2011-08-22T08:33:54.119Z",
    "Season":{"className":"Season","__type":"Pointer","objectId":"WnsdqIlrd6"},
    "Order":24,
    "StartDate":{"iso":"2011-08-30T00:00:00.000Z","__type":"Date"},
    "objectId":"bLdBfhagi9"}
]}        

For reference, I'm deserializing with the following method for both queries:

JavaScriptSerializer jsSerialise = new JavaScriptSerializer();
ObjectIdContainerList contList = jsSerialise.Deserialize<ObjectIdContainerList>(responseString);

Where ObjectIdContainerList is as follows (note - it does not implement all the properties of the original JSON object because I am only interested in getting the objectId property):

[Serializable]
public class ObjectIdContainerList
{
    public ObjectIdContainer[] results { get; set; }
}

[Serializable]
public class ObjectIdContainer
{
    public String objectId { get; set; }
}

The first query deserialises without issue with exactly the same code and objects.

Any suggestions? Would I be best off just going to JSON.NET?


Solution

  • I feel kind of bad for answering my own question, but I ended up solving the problem by using Json.Net to deserialise the object with almost exactly the same code and it worked.

    I'm not inclined to say that this is a bug in the .Net framework, but it kind of feels that way.

    Thanks to those who helped!