使用C#将字符串转换为字典

时间:2019-07-05 08:49:43

标签: c# json dictionary

我从日志服务中获得以下字符串:

[("Browser": "Chrome73 (v 73.0)"), ("UserAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36"), ("Languages": ["nb-NO", "nb;q=0.9", "no;q=0.8", "nn;q=0.7", "en-US;q=0.6", "en;q=0.5"]), ("UserClaim-1-http://schemas.microsoft.com/ws/2008/06/identity/claims/role": "Admin"), ("SessionId": "hhaztuwfpyuobfslljuy4z4e"), ("Cookie-__RequestVerificationToken": "9MJm_A4agsgbe4c_JtAePFnfMLBEgnkc0XhROfDFVd6291SUGtLPAqprsGHBcJw9JDRde6UR_1jHY_Hr4oKi4OZzuUDXqAA6IfeEtr9sxVI1"), ("Cookie-.ASPXAUTH": "AA23B2B1A5C428BFB60E32EA5A78A7D5016D7586F88548C012A1C2C2EB2A34D40A959B43680BCCE9923F1890017F59A3A82E6C1121AF50CF226D638FBCBC40F2D8E2FE4C945B44CC7572717D56C71FCC0B7B285A0EB5379370ADC6BE970E6438"), ("Cookie-ASP.NET_SessionId": "hhaztuwfpyuobfslljuy4z4e"), ("Info-FamilyId": 21267), ("Info-LoggedInUserID": 1), ("Info-MainConsultantUserId": 3)]

我想把它变成字典。我以为我应该做一个简单的任务,但是我一直试图以各种方式来解析字符串,但是没有成功。谁能指出我正确的方向?

我一直在尝试使用:

var x = JsonConvert.DeserializeObject(the_string_above);

我得到一个例外: 解析值时遇到意外字符。 (.path,第1行,位置1)

该格式不是注释中指出的有效JSON,因此问题是如何解析文本...

4 个答案:

答案 0 :(得分:2)

因此,我尝试采用基于Regex的解决方案,但是JSON解决方案会更好,更高效。我已经为您的字符串准备了一个基于正则表达式的示例解决方案。

using System;
using System.Text.RegularExpressions;

public class Program
{
    public static void Main()
    {
         string str = "[(\"Browser\": \"Chrome73 (v 73.0)\"), (\"UserAgent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36\"), (\"Languages\": [\"nb-NO\", \"nb;q=0.9\", \"no;q=0.8\", \"nn;q=0.7\", \"en-US;q=0.6\", \"en;q=0.5\"]), (\"UserClaim-1-http://schemas.microsoft.com/ws/2008/06/identity/claims/role\": \"Admin\"), (\"SessionId\": \"hhaztuwfpyuobfslljuy4z4e\"), (\"Cookie-__RequestVerificationToken\": \"9MJm_A4agsgbe4c_JtAePFnfMLBEgnkc0XhROfDFVd6291SUGtLPAqprsGHBcJw9JDRde6UR_1jHY_Hr4oKi4OZzuUDXqAA6IfeEtr9sxVI1\"), (\"Cookie-.ASPXAUTH\": \"AA23B2B1A5C428BFB60E32EA5A78A7D5016D7586F88548C012A1C2C2EB2A34D40A959B43680BCCE9923F1890017F59A3A82E6C1121AF50CF226D638FBCBC40F2D8E2FE4C945B44CC7572717D56C71FCC0B7B285A0EB5379370ADC6BE970E6438\"), (\"Cookie-ASP.NET_SessionId\": \"hhaztuwfpyuobfslljuy4z4e\"), (\"Info-FamilyId\": 21267), (\"Info-LoggedInUserID\": 1), (\"Info-MainConsultantUserId\": 3)]";
         showMatch(str, @"(?<=\()(.*?)(?=\)[,\]])");
    }

     private static void showMatch(string text, string expr) {
         MatchCollection mc = Regex.Matches(text, expr);

         foreach (Match m in mc) {
            Console.WriteLine(m);
         }
      }
}

这将输出:

"Browser": "Chrome73 (v 73.0)"
"UserAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36"
"Languages": ["nb-NO", "nb;q=0.9", "no;q=0.8", "nn;q=0.7", "en-US;q=0.6", "en;q=0.5"]
"UserClaim-1-http://schemas.microsoft.com/ws/2008/06/identity/claims/role": "Admin"
"SessionId": "hhaztuwfpyuobfslljuy4z4e"
"Cookie-__RequestVerificationToken": "9MJm_A4agsgbe4c_JtAePFnfMLBEgnkc0XhROfDFVd6291SUGtLPAqprsGHBcJw9JDRde6UR_1jHY_Hr4oKi4OZzuUDXqAA6IfeEtr9sxVI1"
"Cookie-.ASPXAUTH": "AA23B2B1A5C428BFB60E32EA5A78A7D5016D7586F88548C012A1C2C2EB2A34D40A959B43680BCCE9923F1890017F59A3A82E6C1121AF50CF226D638FBCBC40F2D8E2FE4C945B44CC7572717D56C71FCC0B7B285A0EB5379370ADC6BE970E6438"
"Cookie-ASP.NET_SessionId": "hhaztuwfpyuobfslljuy4z4e"
"Info-FamilyId": 21267
"Info-LoggedInUserID": 1
"Info-MainConsultantUserId": 3

正在运行的演示:https://dotnetfiddle.net/u1YbBK

使用的正则表达式:(?<=\()(.*?)(?=\)[,\]])

说明:

  1. 正向查找(?<=():\(与字符(完全匹配(区分大小写)
  2. 第一捕获组(。*?):.*?匹配任何字符(行终止符除外)和*?量词-匹配零次和无限制次数,次数尽可能少,根据需要扩展
  3. 正向超前(?=)[,]]):\)从字面上匹配字符)(区分大小写),在[,\]] ,中匹配字符{{ 1}}从字面上(区分大小写),,与字符\]从字面上(区分大小写)匹配

答案 1 :(得分:1)

[{"Browser": "Chrome73 {v 73.0}"}, {"UserAgent": "Mozilla/5.0 {Windows NT 10.0; Win64; x64} AppleWebKit/537.36 {KHTML, like Gecko} Chrome/73.0.3683.86 Safari/537.36"}, {"Languages": ["nb-NO", "nb;q=0.9", "no;q=0.8", "nn;q=0.7", "en-US;q=0.6", "en;q=0.5"]}, {"UserClaim-1-http://schemas.microsoft.com/ws/2008/06/identity/claims/role": "Admin"}, {"SessionId": "hhaztuwfpyuobfslljuy4z4e"}, {"Cookie-__RequestVerificationToken": "9MJm_A4agsgbe4c_JtAePFnfMLBEgnkc0XhROfDFVd6291SUGtLPAqprsGHBcJw9JDRde6UR_1jHY_Hr4oKi4OZzuUDXqAA6IfeEtr9sxVI1"}, {"Cookie-.ASPXAUTH": "AA23B2B1A5C428BFB60E32EA5A78A7D5016D7586F88548C012A1C2C2EB2A34D40A959B43680BCCE9923F1890017F59A3A82E6C1121AF50CF226D638FBCBC40F2D8E2FE4C945B44CC7572717D56C71FCC0B7B285A0EB5379370ADC6BE970E6438"}, {"Cookie-ASP.NET_SessionId": "hhaztuwfpyuobfslljuy4z4e"}, {"Info-FamilyId": 21267}, {"Info-LoggedInUserID": 1}, {"Info-MainConsultantUserId": 3}]

工作正常,只需将'('替换为'{'&')'替换为'}'

https://en.wikipedia.org/wiki/JSON 您可以看到json的工作原理,也许您丢失了一些东西, 并使用http://json.parser.online.fr/尝试您的json字符串。

答案 2 :(得分:1)

Rahul Sharma使用正则表达式进行转换的示例:

using System;
using System.Text.RegularExpressions;
using System.Collections.Generic;

namespace Solution {

    public class Parser {

        public static Dictionary<string,string> parseLoggingInformation(string info) {

            Dictionary<string, string> ret = new Dictionary<string, string>();
            MatchCollection mc = Regex.Matches(info, @"(?<=\()(.*?)(?=\)[,\]])");
            foreach (Match m in mc) {
                string val = m.ToString();
                string[] vals;
                try {
                    vals = val.Split(new string[] { "\": \"" }, StringSplitOptions.None);
                    string tmp = vals[1];
                } catch (Exception) {
                    vals = val.Split(new string[] { "\": " }, StringSplitOptions.None);
                }
                string left = vals[0];
                string right = vals[1];
                ret.Add(left.Substring(1, left.Length - 1), right.Substring(0, right.Length - 1));
            }
            return ret;
        }

        public static void Main(String[] args) {
            GC.Collect();
            Dictionary<string, string> loggingData = parseLoggingInformation("[(\"Browser\": \"Chrome73 (v 73.0)\"), (\"UserAgent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36\"), (\"Languages\": [\"nb-NO\", \"nb;q=0.9\", \"no;q=0.8\", \"nn;q=0.7\", \"en-US;q=0.6\", \"en;q=0.5\"]), (\"UserClaim-1-http://schemas.microsoft.com/ws/2008/06/identity/claims/role\": \"Admin\"), (\"SessionId\": \"hhaztuwfpyuobfslljuy4z4e\"), (\"Cookie-__RequestVerificationToken\": \"9MJm_A4agsgbe4c_JtAePFnfMLBEgnkc0XhROfDFVd6291SUGtLPAqprsGHBcJw9JDRde6UR_1jHY_Hr4oKi4OZzuUDXqAA6IfeEtr9sxVI1\"), (\"Cookie-.ASPXAUTH\": \"AA23B2B1A5C428BFB60E32EA5A78A7D5016D7586F88548C012A1C2C2EB2A34D40A959B43680BCCE9923F1890017F59A3A82E6C1121AF50CF226D638FBCBC40F2D8E2FE4C945B44CC7572717D56C71FCC0B7B285A0EB5379370ADC6BE970E6438\"), (\"Cookie-ASP.NET_SessionId\": \"hhaztuwfpyuobfslljuy4z4e\"), (\"Info-FamilyId\": 21267), (\"Info-LoggedInUserID\": 1), (\"Info-MainConsultantUserId\": 3)]");
        }
    }
}

它将收集的数据保存在Dictionary<string, string>

答案 3 :(得分:0)

好的,所以这个东西看起来几乎像JSON字典一样

  1. 这是一个数组[]而不是字典{}
  2. 键值元组放在()内。

因此,最懒的想法是将外部方括号更改为{},这很简单,然后摆脱不必要的()方括号。您将获得一个有效的JSON,可以使用Newtonsoft.Json或您选择的其他解析器直接对其进行解析。

要解析该内容,我们将贪婪地用引号将所有()括起来,而忽略其余所有内容。

public static string LogToJson(string inputString)
{
    var builder = new StringBuilder("{");
    var escaping = false;

    for (var index = 1 /* Skipping opening [ */ ; index < inputString.Length; ++index)
    {
        var @char = inputString[index];
        switch (@char)
        {
            case '(' when !escaping:
            case ')' when !escaping:
                break;
            case '"':
                escaping ^= true;
                builder.Append(@char);
                break;
            default:
                builder.Append(@char);
                break;
        }
    }

    builder.Length--; // Remove the final ]
    builder.Append("}");
    return builder.ToString();
}

请注意,这完全省略了错误处理,并假定inputString始终正确。因此,当且仅当在删除所有未转义的()括号后输入格式为正确的json时,它才能保证正确的JSON。

对于您的示例字符串,输出为:

{"Browser": "Chrome73 (v 73.0)", "UserAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36", "Languages": ["nb-NO", "nb;q=0.9", "no;q=0.8", "nn;q=0.7", "en-US;q=0.6", "en;q=0.5"], "UserClaim-1-http://schemas.microsoft.com/ws/2008/06/identity/claims/role": "Admin", "SessionId": "hhaztuwfpyuobfslljuy4z4e", "Cookie-__RequestVerificationToken": "9MJm_A4agsgbe4c_JtAePFnfMLBEgnkc0XhROfDFVd6291SUGtLPAqprsGHBcJw9JDRde6UR_1jHY_Hr4oKi4OZzuUDXqAA6IfeEtr9sxVI1", "Cookie-.ASPXAUTH": "AA23B2B1A5C428BFB60E32EA5A78A7D5016D7586F88548C012A1C2C2EB2A34D40A959B43680BCCE9923F1890017F59A3A82E6C1121AF50CF226D638FBCBC40F2D8E2FE4C945B44CC7572717D56C71FCC0B7B285A0EB5379370ADC6BE970E6438", "Cookie-ASP.NET_SessionId": "hhaztuwfpyuobfslljuy4z4e", "Info-FamilyId": 21267, "Info-LoggedInUserID": 1, "Info-MainConsultantUserId": 3}