-1

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?

  • 1
    Does this answer your question? [How can I parse JSON with C#?](https://stackoverflow.com/questions/6620165/how-can-i-parse-json-with-c) – Selvin Jul 09 '20 at 11:53

3 Answers3

3

This looks pretty much as json, so you can try just deserialize it to a collection of Dictionary<string, string>. With Newtonsoft Json.NET it will look like this:

string value = "[{\"name\":\"Sherlock\",\"id\":\"a10ef25\"}]"; // the original value, no need to trim/remove
var collectionOfDicts = JsonConvert.DeserializeObject<List<Dictionary<string,string>>>(value);

To get the key which contains id you can manipulate the collection, for example like this:

var id = collectionOfDicts
    .FirstOrDefault()
    ?.Where(kvp => kvp.Key.Contains("id", StringComparison.InvariantCultureIgnoreCase))
    .Select(kvp => kvp.Value)
    .FirstOrDefault();

UPD

Another option would be using LINQ to JSON from the same library:

var id = JArray.Parse(value)
    .Descendants()
    .OfType<JProperty>()
    .FirstOrDefault(p => p.Name.Contains("id", StringComparison.InvariantCultureIgnoreCase))
    ?.Value
Guru Stron
  • 102,774
  • 10
  • 95
  • 132
1

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);
Roman Marusyk
  • 23,328
  • 24
  • 73
  • 116
0

This is JSON format Use Json Converter

 var value= @"{""name"":""Sherlock"",""id"":""a10ef25"",""date"":""25062019""}";
           
var dict= JsonConvert.DeserializeObject<Dictionary<string, string>>(value); 
Alaa Mohammed
  • 382
  • 2
  • 14