Wednesday, October 31, 2012

JsonConvert.DeserializeObject - Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[System.String]'


Run into this issue while consuming a 3rd party JSON API using JSON.NET.

Complete exception message:

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[System.String]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.

The json string I was trying to deserialize had a field looking like this:

"extras": {},

In my C# class that field was declared as a List<string>. 
By declaring the field as an IDictionary<string, string> instead the problem was solved. 

Lesson learned:
  • If the json value is '[]' => declare the field as List<type>
  • If the json value is '{}' => declare the field IDictionary<type, type>


4 comments:

  1. How to serialize following Json Response

    {"token":{"access_token":"51bee4252fb40411ac83955c2736fdc631795446","expires_in":3600,"token_type":"bearer","scope":null,"refresh_token":"27618c0009f18bfba2a7ab145639fadba6904a43"},"_status":200}

    ReplyDelete