thomasmost
thomasmost

Reputation: 1070

How do I deserialize a Dictionary<string, string[]> in C#?

I have a dynamic JObject that maps a string key to an array of strings. But I'm having trouble deserializing it. I get an uncaught runtime exception each time.

var mapStringToStrings =JsonConvert.DeserializeObject<Dictionary<string,string[]>>(payload.Map);

This is what the JObject contains

   {{
     "c637c0bf-42ec-4f33-a679-5a220260db8e": [
       "dfe7514d-1e42-4c01-ac48-4557e4e34eb3"
     ] 
   }}

And this is the error:

The best overloaded method match for 'Newtonsoft.Json.JsonConvert.DeserializeObject<System.Collections.Generic.Dictionary<string,string[]>>(string)' has some invalid arguments

Help?

Upvotes: 0

Views: 67

Answers (2)

David Siegel
David Siegel

Reputation: 1604

Your JObject is not valid JSON because it has an extra pair of {} around it. The following is valid JSON that deserializes as Dictionary<string, string[]>:

{
  "c637c0bf-42ec-4f33-a679-5a220260db8e": [
    "dfe7514d-1e42-4c01-ac48-4557e4e34eb3"
  ]
}

Upvotes: 3

thomasmost
thomasmost

Reputation: 1070

a dynamic JObject won't deserialize nicely if it's a complex object -- I resolved simply by calling .ToString() on the payload.map before passing it to the deserializer.

Works:

var mapStringToStrings = JsonConvert.DeserializeObject<Dictionary<string,string[]>>(payload.map.ToString());

Upvotes: 0

Related Questions