skip to Main Content

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


  1. 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, your value1, value2, and value3 aren’t variable. (EDIT: Your edit to your question removed the hint that value1, 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:

    string input = $"{{yhxj7027DO=[{value1}], lzpd7453EH=[{value2}, {value3}]}}";
    

    But notice you have to escape the { and } characters by doubling them up. You could use concatenation as well:

    string input = "{yhxj7027DO=[" + value1 + "], lzpd7453EH=["+ value2 + ", " + value3 + "]}";
    

    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.

    Login or Signup to reply.
  2. 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.

    string json = "{yhxj7027DO=[value1], lzpd7453EH=[value2, value3]}";
    json = json.StartsWith("{") ? json.Substring(1) : json;
    json = json.EndsWith("}") ? json.Substring(0, json.Length - 2) : json;
    Dictionary<string, string[]> result = new Dictionary<string, string[]>();
    foreach (var objects in json.Split("],"))
    {
        var jsonSplitted = objects.Split("=");
        if (jsonSplitted?.Length >= 2)
        {
            var property = jsonSplitted[0]?.Trim();
            var value = jsonSplitted[1]?.Substring(1);
            var values = value?.Split(", ");
            if (property != null && values != null)
            {
                result.Add(property, values);
            }
        }
    }
    
    Login or Signup to reply.
  3. You could use regular expressions for that. The following works for your example input but requires polishing.

    Regex re = new Regex(@"((?<key>[a-zA-Z0-9]+)=)[((?<value>w+)[^w]]*)+]");
        string input = "{yhxj7027DO=[value1], lzpd7453EH=[value2, value3]}";
        
        var matches = re.Matches(input);
    
        var results = new Dictionary<string, List<string>>();
        
        foreach(Match match in matches)
        {
            var values = match.Groups["value"].Captures.Select(x => x.Value);
            results.Add(match.Groups["key"].Value, new List<string>(values));
        }
    
        // Print results
        foreach(var pair in results)
        {
            Console.WriteLine($"{pair.Key}: {string.Join(", ", pair.Value)}");  
        }
    
    Login or Signup to reply.
  4. You can use a RegEx to split and then build up the IDictionary<string, List<string>>.

    
    // The regex pattern to use for parsing the input string
    string pattern = @"(([w]+)=[[0-9,]+])";
    
    // Your input string copied from your question
    string input = @"{yhxj7027DO=[3],lzpd7453EH=[2,3]}";
    RegexOptions options = RegexOptions.Multiline;
           
    var dict = new Dictionary<string, List<string>>();
    foreach (Match m in Regex.Matches(input, pattern, options))
    {
        // The groups should match the parts of the input string 
        var index = m.Value.IndexOf("=");
        var first = m.Value.Substring(0, index);
    
        // Remove the leading and ending "[" and "]"
        var rest = m.Value.Substring(index + 1).Replace("[", "").Replace("]","");
        
        // Fill up the dictionarys values with the strings
        dict[first]= rest.Split(",").Select(s => $"{s}").ToList();
    }
    

    Here is a working example in dotnet fiddle

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search