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?
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
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);
This is JSON format Use Json Converter
var value= @"{""name"":""Sherlock"",""id"":""a10ef25"",""date"":""25062019""}";
var dict= JsonConvert.DeserializeObject<Dictionary<string, string>>(value);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.