Search code examples
c#dynamics-crmmicrosoft-dynamics

How to Convert a string received from dynamics CRM to Dictionary in C#


I'm dynamics CRM developer an I'm writing a codeactivity where I'm receiving field value in format like:

[{"name":"Sherlock","id":"a10ef25"}] 

I want to convert this value to dictionary format. I'm thinking of using ToDictionary() method after removing the [] from the value by converting it to string like this:

{"name":"Sherlock","exid":"a10ef25"}

I need the value of Key which contains "id" but the number of pairs in the string can be more than 2 also some times like:

{"name":"Sherlock","id":"a10ef25","date":"25062019"}.

var value=[{"name":"Sherlock","id":"a10ef25"}]; // i'm receiving it from crm & converting to string
var dict=value.Substring(1.value.Length-1);

I'm unable to go forward than this. can anyone help?


Solution

  • One more solution

    var value ="[{ \"name\":\"Sherlock\",\"id\":\"a10ef25\"}]".TrimStart('[').TrimEnd(']');
    var dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(value);
    var id = dict["id"]; // or dict.TryGetValue("id", out string id);