2

I have the following string:

{"key1":"value1","key2":"value2,some other part of value2"}

I can use the following long syntax to split this:

var s = someString.Split(new[] {"\",\""}, StringSplitOptions.RemoveEmptyEntries);
var firstEntryValue = s[0].Split(':')[1];
var secondEntryValue = s[1].Split(':')[1];

Since this string is basically a Dictionary<string,string>, how can I pull the whole thing into that type in basically one line?

I've seen something like this:

var s = someString.Split(new[] {"\",\""}, StringSplitOptions.RemoveEmptyEntries)
  .Select(p => p.Split(':'))
  .ToDictionary(split => split[0], split => split[1]);

But it throws and index out of bounds error. Is there some similar syntax that will work?

4thSpace
  • 43,672
  • 97
  • 296
  • 475

1 Answers1

6

Since the string follows JSON format, splitting it is not a good option - precisely because of the issues that you mention.

You can use JsonConvert instead:

var res = JsonConvert.DeserializeObject<Dictionary<string,string>>(inputString);
Community
  • 1
  • 1
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • 1
    Might be worth mentioning that he'll need the JSON.NET nuget package to use JsonConvert – rmc00 Jul 20 '16 at 15:58