.net使用Newtonsoft.Json.dll解析json过程的几种特殊情况处理

.net用来解析json的库 Newtonsoft.Json.dll 按理说已十分强大,但调用人家的json总有意想不到的情况发生,你没办法要求别人传给你标准的json字符串给你
下面是我遇到的几种情况及解决方法:
情况1,字段中包含英文引号:{"title": "超清爽"夏装"连衣裙","flag": 0}
情况2,{}开头结尾的字段前后有引号:{"content" : "{"微信":"","QQ":"888","微博":"xxx@sina.cn"}"} (主意:同时要避免误处理这种可以解析的情况:{"content" : "{优惠活动} 超清爽夏装连衣裙"} )
情况3,字段中有转义字符:{"content" : "{"微信":"","QQ":"888","微博":"xxx@sina.cn"}

转换方法:

        /// <summary>
        /// 规范化json字符:
        /// 1.替代字段中的英文引号(")为中文引号(“);
        /// 2.去掉以{}开头结尾的字段前后引号,注意:情况1和2同时在一个字段出现情况没考虑到;
        /// 3.去掉所有转义符"\"。
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static string jsonString(string s)
        {
            string str = s.Replace("\","");//情况3:字符中有转义符号
            char[] temp = str.ToCharArray();
            int n = temp.Length;
            for (int i = 0; i < n; i++)
            {
                if (!(temp[i] == ':' && i + 2 < n))
                    continue;
                int start = i + 2;

                if (temp[i + 1] != '"')
                {
                    if (temp[i + 1] == ' ' && temp[i + 2] == '"')
                        start++;
                    else
                        continue;
                }

                //遇到情况2,去掉{}前后引号
                if (temp[start] == '{')
                {
                    for (int k = start; k+1 < n; k++)
                    {
                        if (temp[k] == '}')
                        {
                            if (temp[k + 1] == '"')
                            {
                   temp[start - 1] = ' ';    temp[k
+ 1] = ' '; } } } continue;//注意:情况1和2同时在一个字段出现情况没考虑到 } //遇到情况1,去掉英文引号 for (int j = start; j + 1 < n; j++) { if (temp[j] == '"') { if (temp[j + 1] != ',' && temp[j + 1] != '}' && temp[j + 1] != '"') { temp[j] = ''; } else if (temp[j + 1] == ',' || temp[j + 1] == '}' && temp[j + 1] != '"') { break; } } } } return new string(temp); }

测试代码:

         //情况1示例:
         string json = "{"title": "超清爽"夏装"连衣裙","flag": 0}";
         //情况2示例:
         //string json = "{"content" : "{"微信":"","QQ":"888","微博":"xxx@sina.cn"}";
         //情况3示例:
         //string json = "{"content" : "{\"微信\":\"\",\"QQ\":\"888\",\"微博\":\"xxx@sina.cn\"}";
         string jstr = jsonString(json);
         JObject jo = JObject.Parse(jstr);
原文地址:https://www.cnblogs.com/zhaohz/p/4610070.html