Chris Westbrook
Chris Westbrook

Reputation: 2090

"Value cannot be null" error when deserializing json using C# / JavaScriptSerializer

I am trying to deserialize some JSON that I am grabbing from an asmx service into a list of objects. All of the fields in the class match fields in the JSON, the JSON is coming back valid, but I get the seemingly cryptic error:

Value cannot be null. Parameter name: type.

There is no parameter named type in any of my objects. Has anyone seen this before?

Here is the code that is throwing the error.

System.Web.Script.Serialization.JavaScriptSerializer serr = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Rejection> l = serr.Deserialize<List<Rejection>>(json);

json is a string declared earlier and coming back with valid json that matches the field in my class. Does the class you are deserializing to's name have to match what is in the __type attribute in the json?

Upvotes: 5

Views: 4801

Answers (3)

Justin
Justin

Reputation: 86729

I've just got this too - I believe that its something to do with the serialiser being initialised without a type resolver:

// The following fails
var serialiser = new JavaScriptSerializer();
MyClass obj = serialiser.Deserialize<MyClass>(input);

// But the following works fine
var serialiser = new JavaScriptSerializer(new SimpleTypeResolver());
MyClass obj = serialiser.Deserialize<MyClass>(input);

I found that I only got this error when deserialising JSON that had the __type attribute present (which is only present when serialised using a type resolver). If your JSON doesn't have the __type attribute, then deserialisation appears to work fine using either of the above.

Upvotes: 3

Chris Westbrook
Chris Westbrook

Reputation: 2090

I solved my problem by avoiding the javascript serializer all together and using the json.net library. Worked like a charm.

Upvotes: 0

Rubens Farias
Rubens Farias

Reputation: 57946

I'm not sure exactly where is your problem, but try following code:


string input = "..."; // your asmx data
JavaScriptSerializer serializer = new JavaScriptSerializer();
List<YourCustomClass> novos = new List<YourCustomClass>(
    serializer.Deserialize<YourCustomClass[]>(input)));

Upvotes: 0

Related Questions