1. 程式人生 > >.NET 2.0輕量級的JSON轉換程式碼

.NET 2.0輕量級的JSON轉換程式碼

複製程式碼
 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; } } }
複製程式碼