發布一款輕量級的JSON轉換代碼


.NET FrameWork 2.0 並沒有提供JSON 字符串對象化工具,因此嘗試寫了這個轉換器, 目前已投入使用,分享一下. 實現方式是:正則 + 遞歸. 對需要轉換的Json 字符串復雜度沒有要求. 歡迎測試,並提供反饋,謝謝. 第一次運行,有點慢,估計是初使化正則占用了時間,這些正則是靜態的,之后的轉換會加快.

/*create by ayymbirst @gmail.com */
using
System; using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; namespace JsonConver { /// <summary> /// 節點枚舉 /// </summary> public enum NodeType { /// <summary> /// 標識數組 /// </summary> IsArray , /// <summary> /// 標識對象 /// </summary> IsObject , /// <summary> /// 標識元數據 /// </summary> IsOriginal , /// <summary> /// 未知格式 /// </summary> Undefined } //描述Json節點 public class JsonNode { public NodeType NodeType; public List<JsonNode> List; public Dictionary<string, JsonNode> DicObject; public string Value; } /// <summary> /// json 字符串對象化 /// </summary> public class ConvertJsonObject { static string regTxt = "({0}[^{0}{1}]*(((?'Open'{0})[^{0}{1}]*)+((?'-Open'{1})[^{0}{1}]*)+)*(?(Open)(?!)){1})"; //匹配字符串(單雙引號范圍) static string regKeyValue = "({0}.{1}?(?<!\\\\){0})"; //判斷是否包含單,雙引號 //匹配元數據(不包含對象,數組) static string regOriginalValue = string.Format("({0}|{1}|{2})", string.Format(regKeyValue, "'", "*"), string.Format(regKeyValue, "\"", "*"), "\\w+"); //匹配value (包含對象數組) static string regValue = string.Format("({0}|{1}|{2})", regOriginalValue //字符 , string.Format(regTxt, "\\[", "\\]"), string.Format(regTxt, "\\{", "\\}")); //匹配鍵值對 static string regKeyValuePair = string.Format("\\s*(?<key>{0}|{1}|{2})\\s*:\\s*(?<value>{3})\\s*" , string.Format(regKeyValue, "'", "+"), string.Format(regKeyValue, "\"", "+"), "([^ :,]+)" //匹配key , regValue); //匹配value /// <summary> /// 判斷是否是對象 /// </summary> static Regex RegJsonStrack1 = new Regex(string.Format("^\\{0}(({2})(,(?=({2})))?)+\\{1}$", "{", "}", regKeyValuePair), RegexOptions.Compiled); /// <summary> /// 判斷是否是序列 /// </summary> static Regex RegJsonStrack2 = new Regex(string.Format("^\\[(({0})(,(?=({0})))?)+\\]$", regValue), RegexOptions.Compiled); /// <summary> /// 判斷鍵值對 /// </summary> static Regex RegJsonStrack3 = new Regex(regKeyValuePair, RegexOptions.Compiled); //匹配value static Regex RegJsonStrack4 = new Regex(regValue, RegexOptions.Compiled); //匹配元數據 static Regex RegJsonStrack6 = new Regex(string.Format("^{0}$", regOriginalValue), RegexOptions.Compiled); //移除兩端[] , {} static Regex RegJsonRemoveBlank = new Regex("(^\\s*[\\[\\{'\"]\\s*)|(\\s*[\\]\\}'\"]\\s*$)", RegexOptions.Compiled); string JsonTxt; public ConvertJsonObject(string json) { //去掉換行符 json = Regex.Replace(json, "[\r\n]", ""); JsonTxt = json; } /// <summary> /// 判斷節點內型 /// </summary> /// <param name="json"></param> /// <returns></returns> public NodeType MeasureType(string json) { if (RegJsonStrack1.IsMatch(json)) { return NodeType.IsObject; } if (RegJsonStrack2.IsMatch(json)) { return NodeType.IsArray; } if (RegJsonStrack6.IsMatch(json)) { return NodeType.IsOriginal; } return NodeType.Undefined; } /// <summary> /// json 字符串序列化為對象 /// </summary> /// <param name="json"></param> /// <returns></returns> public JsonNode SerializationJsonNodeToObject() { return SerializationJsonNodeToObject(JsonTxt); } /// <summary> /// json 字符串序列化為對象 /// </summary> /// <param name="json"></param> /// <returns></returns> public JsonNode SerializationJsonNodeToObject(string json) { json = json.Trim(); NodeType nodetype = MeasureType(json); if (nodetype == NodeType.Undefined) { throw new Exception("未知格式Json: " + json); } JsonNode newNode = new JsonNode(); newNode.NodeType = nodetype; if (nodetype == NodeType.IsArray) { json = RegJsonRemoveBlank.Replace(json, ""); MatchCollection matches = RegJsonStrack4.Matches(json); newNode.List = new List<JsonNode>(); foreach (Match match in matches) { if (match.Success) { newNode.List.Add(SerializationJsonNodeToObject(match.Value)); } } } else if (nodetype == NodeType.IsObject) { json = RegJsonRemoveBlank.Replace(json, ""); MatchCollection matches = RegJsonStrack3.Matches(json); newNode.DicObject = new Dictionary<string, JsonNode>(); string key; foreach (Match match in matches) { if (match.Success) { key = RegJsonRemoveBlank.Replace(match.Groups["key"].Value, ""); if (newNode.DicObject.ContainsKey(key)) { throw new Exception("json 數據中包含重復鍵, json:" + json); } newNode.DicObject.Add(key, SerializationJsonNodeToObject(match.Groups["value"].Value)); } } } else if (nodetype == NodeType.IsOriginal) {  newNode.Value = RegJsonRemoveBlank.Replace(json, "").Replace("\\r\\n", "\r\n"); } return newNode; } } }

其中 JsonNode 是返回解析結果

NodeType 是枚舉類型,表示當前節點是什么類型.

IsArray: JsonNode.List

IsObject:JsonNode.DicObject

IsOriginal:JsonNode.Value

Json 字符串換行請用雙斜杠,如 "aa\\r\\nbb",表示aa,bb 為相鄰兩行.

 

調用代碼:

JsonConver.ConvertJsonObject jsonObj = new JsonConver.ConvertJsonObject("{'a':11,'b':[1,2,3],'c':{'a':1,'b':[1,2,3]}}");
            JsonConver.JsonNode node = jsonObj.SerializationJsonNodeToObject();
            if (node.NodeType == JsonConver.NodeType.IsObject)
            {
                if (node.DicObject["a"].NodeType == JsonConver.NodeType.IsOriginal)
                {
                    Console.Write("key:a , value:");
                    Console.Write(node.DicObject["a"].Value);
                    Console.WriteLine();
                }

                if (node.DicObject["b"].NodeType == JsonConver.NodeType.IsArray)
                {
                    Console.Write("key:b,value for first:");
                    Console.Write(node.DicObject["b"].List[0].Value);
                    Console.WriteLine();
                }

                if (node.DicObject["c"].NodeType == JsonConver.NodeType.IsObject)
                {
                    if (node.DicObject["c"].DicObject["a"].NodeType == JsonConver.NodeType.IsOriginal)
                    {
                        Console.Write("key:c  子對象值: , value:");
                        Console.Write(node.DicObject["c"].DicObject["a"].Value);
                        Console.WriteLine();
                    }
                }
            }

       

                Console.Read();


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM