I have a string "{yhxj7027DO=[3], lzpd7453EH=[2, 3]}"
. I would like to convert it to a Dictionary of type new Dictionary<string, List<string>>()
. I tried the following
string = "{yhxj7027DO=[value1], lzpd7453EH=[value2, value3]}"
var strArr = input.Replace("{", "").Replace("}", "").Split("],", StringSplitOptions.TrimEntries);
for (int i = 0; i < strArr.Length - 1; i++) strArr[i] += "]";
StringBuilder sb = new StringBuilder("{");
foreach (var item in strArr)
{
var arr = item.Split("=");
sb.Append(""" + arr[0] + """ + ":" + arr[1] + ",");
}
sb.Append("}");
var json = sb.ToString().Replace(",}", "}");
Dictionary<string, string[]> result = JsonConvert.DeserializeObject<Dictionary<string, string[]>>(json);
I have the following error: Unexpected character encountered while parsing number: :. Path 'lzpd7453EH[0]', line 1, position 36.
What could be the problem?
4
Answers
Your problem is syntax in how you are defining the input string. First, you aren’t naming the variable
input
, which seems to be what the rest of your code expects. Second, yourvalue1
,value2
, andvalue3
aren’t variable. (EDIT: Your edit to your question removed the hint thatvalue1
, etc. should be interpolated, but I’ve left the below information in case you do want to interpolate those values.)You can use string interpolation:
But notice you have to escape the
{
and}
characters by doubling them up. You could use concatenation as well:If you need to include double quotes in the string literal than you can use a "raw string literal" or just escape the quotes with a
character.
Hopefully you don’t mind if I changed it up a bit. This achieves what you want I believe. I build in some safeguards incase string doesn’t contain what you expect.
You could use regular expressions for that. The following works for your example input but requires polishing.
You can use a
RegEx
to split and then build up theIDictionary<string, List<string>>
.Here is a working example in dotnet fiddle