http://www.sufeinet.com/plugin.php?id=keke_group

苏飞论坛

 找回密码
 马上注册

QQ登录

只需一步,快速开始

分布式系统框架(V2.0) 轻松承载百亿数据,千万流量!讨论专区 - 源码下载 - 官方教程

HttpHelper爬虫框架(V2.7-含.netcore) HttpHelper官方出品,爬虫框架讨论区 - 源码下载 - 在线测试和代码生成

HttpHelper爬虫类(V2.0) 开源的爬虫类,支持多种模式和属性 源码 - 代码生成器 - 讨论区 - 教程- 例子

查看: 3974|回复: 6

[其他] 帮忙看看 Json字符串 转 数组 为什么老是出错

[复制链接]
发表于 2014-2-14 13:33:42 | 显示全部楼层 |阅读模式
[C#] 纯文本查看 复制代码
    public class JSONConvert
    {
        #region 全局变量
        private JSONObject _json = new JSONObject();//寄存器
        private readonly string _SEMICOLON = "@semicolon";//分号转义符
        private readonly string _COMMA = "@comma"; //逗号转义符
        #endregion
        #region 字符串转义
        /// <summary>
        /// 字符串转义,将双引号内的:和,分别转成_SEMICOLON和_COMMA
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        private string StrEncode(string text)
        {
            System.Text.RegularExpressions.MatchCollection matches = System.Text.RegularExpressions.Regex.Matches(text, "\\\"[^\\\"]+\\\"");
            foreach (System.Text.RegularExpressions.Match match in matches)
            {
                text = text.Replace(match.Value, match.Value.Replace(":", _SEMICOLON).Replace(",", _COMMA));
            }
            return text;
        }
        /// <summary>
        /// 字符串转义,将_SEMICOLON和_COMMA分别转成:和,
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        private string StrDecode(string text)
        {
            return text.Replace(_SEMICOLON, ":").Replace(_COMMA, ",");
        }
        #endregion
        #region JSON最小单元解析
        /// <summary>
        /// 最小对象转为JSONObject
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        private JSONObject DeserializeSingletonObject(string text)
        {
            JSONObject jsonObject = new JSONObject();
            System.Text.RegularExpressions.MatchCollection matches = System.Text.RegularExpressions.Regex.Matches(text, "(\\\"(?<key>[^\\\"]+)\\\":\\\"(?<value>[^,\\\"]*)\\\")|(\\\"(?<key>[^\\\"]+)\\\":(?<value>[^,\\\"\\}]*))");
            foreach (System.Text.RegularExpressions.Match match in matches)
            {
                string value = match.Groups["value"].Value;
                jsonObject.Add(match.Groups["key"].Value, _json.ContainsKey(value) ? _json[value] : StrDecode(value));
            }
            return jsonObject;
        }
        /// <summary>
        /// 最小数组转为JSONArray
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        private JSONArray DeserializeSingletonArray(string text)
        {
            JSONArray jsonArray = new JSONArray();
            System.Text.RegularExpressions.MatchCollection matches = System.Text.RegularExpressions.Regex.Matches(text, "(\\\"(?<value>[^,\\\"]+)\")|(?<value>[^,\\[\\]]+)");
            foreach (System.Text.RegularExpressions.Match match in matches)
            {
                string value = match.Groups["value"].Value;
                jsonArray.Add(_json.ContainsKey(value) ? _json[value] : StrDecode(value));
            }
            return jsonArray;
        }
        /// <summary>
        /// 反序列化
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        private string Deserialize(string text)
        {
            text = StrEncode(text);//转义;和,
            int count = 0;
            string key = string.Empty;
            string pattern = "(\\{[^\\[\\]\\{\\}]+\\})|(\\[[^\\[\\]\\{\\}]+\\])";
            while (System.Text.RegularExpressions.Regex.IsMatch(text, pattern))
            {
                System.Text.RegularExpressions.MatchCollection matches = System.Text.RegularExpressions.Regex.Matches(text, pattern);
                foreach (System.Text.RegularExpressions.Match match in matches)
                {
                    key = "___key" + count + "___";
                    if (match.Value.Substring(0, 1) == "{")
                        _json.Add(key, DeserializeSingletonObject(match.Value));
                    else
                        _json.Add(key, DeserializeSingletonArray(match.Value));
                    //foreach (var item in _json)
                    //{
                    //    text = item.Key + ":" + item.Value+",";
                    //}
                    text = text.Replace(match.Value, key);//.Replace(match.Value, key)
                    count++;
                }
            }
            return text;
        }
        #endregion
        #region 公共接口
        /// <summary>
        /// 序列化JSONObject对象
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public JSONObject DeserializeObject(string text)
        {
            string res = string.Empty;
            if (text.Contains('('))
            {
                res = Stringoperation.Between(text, "(", ")");
                return _json[Deserialize(res)] as JSONObject;
            }
            else
            {
                return _json[Deserialize(text)] as JSONObject;
            }
        }
        /// <summary>
        /// 序列化JSONArray对象
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public JSONArray DeserializeArray(string text)
        {
            string res = string.Empty;
            if (text.Contains('('))
            {
                res = Stringoperation.Between(text, "(", ")");
                return _json[Deserialize(res)] as JSONArray;
            }
            else
            {
                return _json[Deserialize(text)] as JSONArray;
            }

        }
        /// <summary>
        /// 反序列化JSONObject对象
        /// </summary>
        /// <param name="jsonObject"></param>
        /// <returns></returns>
        public string SerializeObject(JSONObject jsonObject)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("{");
            foreach (KeyValuePair<string, object> kvp in jsonObject)
            {
                if (kvp.Value is JSONObject)
                {
                    sb.Append(string.Format("\"{0}\":{1},", kvp.Key, SerializeObject((JSONObject)kvp.Value)));
                }
                else if (kvp.Value is JSONArray)
                {
                    sb.Append(string.Format("\"{0}\":{1},", kvp.Key, SerializeArray((JSONArray)kvp.Value)));
                }
                else if (kvp.Value is String)
                {
                    sb.Append(string.Format("\"{0}\":\"{1}\",", kvp.Key, kvp.Value));
                }
                else
                {
                    sb.Append(string.Format("\"{0}\":\"{1}\",", kvp.Key, ""));
                }
            }
            if (sb.Length > 1)
                sb.Remove(sb.Length - 1, 1);
            sb.Append("}");
            return sb.ToString();
        }
        /// <summary>
        /// 反序列化JSONArray对象
        /// </summary>
        /// <param name="jsonArray"></param>
        /// <returns></returns>
        public string SerializeArray(JSONArray jsonArray)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("[");
            for (int i = 0; i < jsonArray.Count; i++)
            {
                if (jsonArray[i] is JSONObject)
                {
                    sb.Append(string.Format("{0},", SerializeObject((JSONObject)jsonArray[i])));
                }
                else if (jsonArray[i] is JSONArray)
                {
                    sb.Append(string.Format("{0},", SerializeArray((JSONArray)jsonArray[i])));
                }
                else if (jsonArray[i] is String)
                {
                    sb.Append(string.Format("\"{0}\",", jsonArray[i]));
                }
                else
                {
                    sb.Append(string.Format("\"{0}\",", ""));
                }
            }
            if (sb.Length > 1)
                sb.Remove(sb.Length - 1, 1);
            sb.Append("]");
            return sb.ToString();
        }
        #endregion
    }
    /// <summary>
    /// 类  名:JSONObject
    /// 描  述:JSON对象类
    /// 继承Dictionary<TKey, TValue>代替this[]
    /// </summary>
    public class JSONObject : Dictionary<string, object>
    { }
    /// <summary>
    /// 类  名:JSONArray
    /// 描  述:JSON数组类
    ///继承List<T>代替this[]
    /// </summary>
    public class JSONArray : List<object>
    { }








1. 开通SVIP会员,免费下载本站所有源码,不限次数据,不限时间
2. 加官方QQ群,加官方微信群获取更多资源和帮助
3. 找站长苏飞做网站、商城、CRM、小程序、App、爬虫相关、项目外包等点这里
 楼主| 发表于 2014-2-14 13:34:07 | 显示全部楼层
帖子 限制大小,分开发.....
[C#] 纯文本查看 复制代码
以下是实现代码:
[mw_shl_code=csharp,true] var jsonString = @"[{""Id"": ""b3ec4e5c"",""AlbumName"": ""Dirty Deeds Done Dirt Cheap"",""Artist"": ""AC/DC"",
""YearReleased"": 1976,
""Entered"": ""2012-03-16T00:13:12.2810521-10:00"",
""AlbumImageUrl"": ""http://ecx.images-amazon.com/images/I/61kTaH-uZBL._AA115_.jpg"",
""AmazonUrl"": ""http://www.amazon.com/gp/product/…ASIN=B00008BXJ4"",
""Songs"": [
{
""AlbumId"": ""b3ec4e5c"",
""SongName"": ""Dirty Deeds Done Dirt Cheap"",
""SongLength"": ""4:11""
},
{
""AlbumId"": ""b3ec4e5c"",
""SongName"": ""Love at First Feel"",
""SongLength"": ""3:10""
},
{
""AlbumId"": ""b3ec4e5c"",
""SongName"": ""Big Balls"",
""SongLength"": ""2:38""
}
]
},
{
""Id"": ""7b919432"",
""AlbumName"": ""End of the Silence"",
""Artist"": ""Henry Rollins Band"",
""YearReleased"": 1992,
""Entered"": ""2012-03-16T00:13:12.2800521-10:00"",
""AlbumImageUrl"": ""http://ecx.images-amazon.com/images/I/51FO3rb1tuL._SL160_AA160_.jpg"",
""AmazonUrl"": ""http://www.amazon.com/End-Silence-Rollins-Band/dp/B0000040OX/ref=sr_1_5?ie=UTF8&qid=1302232195&sr=8-5"",
""Songs"": [
{
""AlbumId"": ""7b919432"",
""SongName"": ""Low Self Opinion"",
""SongLength"": ""5:24""
},
{
""AlbumId"": ""7b919432"",
""SongName"": ""Grip"",
""SongLength"": ""4:51""
}
]
}
]";
JSONConvert json = new JSONConvert();
JSONArray jsonArray = json.DeserializeArray(jsonString);


懂的帮我看看。。谢谢了[/mw_shl_code]
发表于 2014-2-14 14:30:56 | 显示全部楼层
好长的代码吗,你还不如直接说要把什么格式的数据转成什么格式的数组来的快。这样说不定我们还能自己写写
 楼主| 发表于 2014-2-14 14:48:47 | 显示全部楼层
站长苏飞 发表于 2014-2-14 14:30
好长的代码吗,你还不如直接说要把什么格式的数据转成什么格式的数组来的快。这样说不定我们还能自己写写
[C#] 纯文本查看 复制代码
var jsonString = @"[{""Id"": ""b3ec4e5c"",""AlbumName"": ""Dirty Deeds Done Dirt Cheap"",""Artist"": ""AC/DC"",
""YearReleased"": 1976,
""Entered"": ""2012-03-16T00:13:12.2810521-10:00"",
""AlbumImageUrl"": ""http://ecx.images-amazon.com/images/I/61kTaH-uZBL._AA115_.jpg"",
""AmazonUrl"": ""http://www.amazon.com/gp/product/…ASIN=B00008BXJ4"",
""Songs"": [
{
""AlbumId"": ""b3ec4e5c"",
""SongName"": ""Dirty Deeds Done Dirt Cheap"",
""SongLength"": ""4:11""
},
{
""AlbumId"": ""b3ec4e5c"",
""SongName"": ""Love at First Feel"",
""SongLength"": ""3:10""
},
{
""AlbumId"": ""b3ec4e5c"",
""SongName"": ""Big Balls"",
""SongLength"": ""2:38""
}
]
},
{
""Id"": ""7b919432"",
""AlbumName"": ""End of the Silence"",
""Artist"": ""Henry Rollins Band"",
""YearReleased"": 1992,
""Entered"": ""2012-03-16T00:13:12.2800521-10:00"",
""AlbumImageUrl"": ""http://ecx.images-amazon.com/images/I/51FO3rb1tuL._SL160_AA160_.jpg"",
""AmazonUrl"": ""http://www.amazon.com/End-Silence-Rollins-Band/dp/B0000040OX/ref=sr_1_5?ie=UTF8&qid=1302232195&sr=8-5"",
""Songs"": [
{
""AlbumId"": ""7b919432"",
""SongName"": ""Low Self Opinion"",
""SongLength"": ""5:24""
},
{
""AlbumId"": ""7b919432"",
""SongName"": ""Grip"",
""SongLength"": ""4:51""
}
]
}
]";



转换为数组 形式
发表于 2014-2-14 14:53:47 | 显示全部楼层
直接定义个这样的对象可以序列化这个结构,你So一下具体方法。
 楼主| 发表于 2014-2-14 15:22:02 | 显示全部楼层
站长苏飞 发表于 2014-2-14 14:53
直接定义个这样的对象可以序列化这个结构,你So一下具体方法。

就是想做个通用的 好调用,还是调用别人的DLL,简单了事
发表于 2014-2-14 18:00:53 | 显示全部楼层
南方 发表于 2014-2-14 15:22
就是想做个通用的 好调用,还是调用别人的DLL,简单了事

还是调用Dll吧,这东西写起来费劲。呵呵
您需要登录后才可以回帖 登录 | 马上注册

本版积分规则

QQ|手机版|小黑屋|手机版|联系我们|关于我们|广告合作|苏飞论坛 ( 豫ICP备18043678号-2)

GMT+8, 2024-11-23 22:57

© 2014-2021

快速回复 返回顶部 返回列表