Reputation: 1739
I'm using JSON.NET to deserialize some JSON returned from a web service. Unfortunately, i'm getting the following err:
Cannot deserialize JSON array into type 'System.Collections.Generic.Dictionary`2[System.String,System.String]'.
but i have no idea how to debug it. is there a way to have it tell me what the offending JSON is? or even what it's trying to deserialize it to? unfortunately this is part of a larger object hierarchy, so it's not just a simple piece of JSON. i've tried stepping through the code, but there's miles of it and little documentation. If it could at least tell me the offending piece, then i can see if maybe i cocked up my object definition or something.
Upvotes: 15
Views: 13045
Reputation: 1723
If you want to deserialize what you're converting from json into C# classes there's something built into json.net for this. Just create a settings object and pass it into your deserializeobject call:
if (!string.IsNullOrEmpty(json))
{
var settings = new JsonSerializerSettings
{
Error = (sender, args) =>
{
if (System.Diagnostics.Debugger.IsAttached)
{
System.Diagnostics.Debugger.Break();
}
}
};
result = JsonConvert.DeserializeObject<T>(json, settings);
}
Then when there are errors in the deserialization process (like a mismapped C# class -> json object) it'll break in the debugger. Inspect the args object and you'll see a property called CurrentObject. This is the C# class that the parser is trying to deserialize the JSON into (and will provide details about what the error might be).
Hope that helps.
Upvotes: 30
Reputation: 1739
Figured out where to look after walking through tons of code. line 1118ish JsonSerializerInternalReader is:
SetPropertyValue(property, reader, newObject);
and if you put a breakpoint there and watch "property" you can see what property is getting serialized. since it does it in order of the json string you can watch that and see the last one to successfully get set. then you at least know where the serializer is failing.
it would be helpful, however, if JSON.net raised at least the property name in the error, but until that happens, this seems to be the next best thing.
Upvotes: 6
Reputation: 4052
Based on the information you've provided, I would start by looking for an object that has a property of type Dictionary. That's probably your problem class.
Upvotes: 0