C# Json解析類,可用

    public class AnalyzeJson
    {
        public string error = null;
        string val = "";
        StringBuilder key = new StringBuilder();
        StringBuilder value = new StringBuilder();
        List<AnalyzeJson> array = new List<AnalyzeJson>();
        Dictionary<string, AnalyzeJson> dic = new Dictionary<string, AnalyzeJson>();

        int big = 0;
        int middle = 0;

        bool isStart = false;

        public AnalyzeJson() { }

        public AnalyzeJson(string json)
        {
            val = json;
            if (json == null) return;
            //if (json.IndexOf("\\\"") != -1)
            //    json = json.Replace("\\\"", "\"");
            //if (json.IndexOf("\"{") != -1)
            //    json = json.Replace("\"{", "{");
            //if (json.IndexOf("\"}") != -1)
            //    json = json.Replace("}\"", "}");

            try
            {
                if (json[0] == '[')
                {
                    handleArray(json);
                    return;
                }

                int length = json.Length;

                for (int i = 0; i < length; i++)
                {
                    bool isNext = false;
                    //跳過開頭
                    while (i < length && json[i++] != '"') ;
                    //讀名稱
                    while (i < length && json[i] != '"')
                        key.Append(json[i++]);
                    while (i < length && json[i++] != ':') ;
                    //讀內容
                    while (i < length && json[i] != '"' && json[i] != '[' && json[i] != '{')
                    {
                        //null
                        if (json[i] == 'n' &&
                            json[i + 1] == 'u' &&
                            json[i + 2] == 'l' &&
                            json[i + 3] == 'l')
                        {
                            dic.Add(key.ToString(), null);
                            key.Clear();
                            value.Clear();
                            i += 3;
                            isNext = true;
                            break;
                        }
                        //bool
                        else if (json[i] == 't' &&
                            json[i + 1] == 'r' &&
                            json[i + 2] == 'u' &&
                            json[i + 3] == 'e')
                        {
                            dic.Add(key.ToString(), new AnalyzeJson("true"));
                            key.Clear();
                            value.Clear();
                            i += 3;
                            isNext = true;
                            break;
                        }
                        //bool
                        else if (json[i] == 'f' &&
                            json[i + 1] == 'a' &&
                            json[i + 2] == 'l' &&
                            json[i + 3] == 's' &&
                            json[i + 4] == 'e')
                        {
                            dic.Add(key.ToString(), new AnalyzeJson("false"));
                            key.Clear();
                            value.Clear();
                            i += 4;
                            isNext = true;
                            break;
                        }
                        //數值
                        if (json[i] >= '0' && json[i] <= '9')
                        {
                            while (json[i] != ',' && json[i] != '}')
                                value.Append(json[i++]);
                            i--;
                            dic.Add(key.ToString(), new AnalyzeJson(value.ToString().Trim()));
                            key.Clear();
                            value.Clear();
                            isNext = true;
                            break;
                        }
                        ///////////////////////////////////////////////////////////
                        i++;
                    }
                    if (isNext) continue;
                    i++;
                    if (i - 1 > length || i > length) return;
                    if (json[i - 1] == '"')
                    {
                        int endI = findEnd(json, i - 1);

                        //while (i < length && json[i] != '"')
                        //    value.Append(json[i++]);
                        while(i < endI)
                            value.Append(json[i++]);
                        dic.Add(key.ToString(), new AnalyzeJson(value.ToString(), true));
                        key.Clear();
                        value.Clear();
                    }
                    else if (json[i - 1] == '{')
                    {
                        value.Append("{");
                        while (
                            (i < length && json[i] != '}' && isStart == false) ||
                            (i < length && json[i] == '}' && isStart == false && big != 0) ||
                            (i < length && isStart))
                        {
                            if (isStart == false && json[i] == '{')
                                big++;
                            if (isStart == false && json[i] == '}')
                                big--;
                            value.Append(json[i++]);
                        }
                        value.Append("}");
                        AnalyzeJson mj = new AnalyzeJson(value.ToString());
                        value.Clear();
                        dic.Add(key.ToString(), mj);
                        key.Clear();
                        value.Clear();
                    }
                    else
                    {
                        value.Append("[");
                        while (
                            (i < length && json[i] != ']' && isStart == false) ||
                            (i < length && json[i] == ']' && isStart == false && middle != 0) ||
                            (i < length && isStart))
                        {
                            if (isStart == false && json[i] == '[')
                                middle++;
                            if (isStart == false && json[i] == ']')
                                middle--;
                            value.Append(json[i++]);
                        }
                        value.Append("]");
                        AnalyzeJson mj = new AnalyzeJson(value.ToString());
                        value.Clear();
                        dic.Add(key.ToString(), mj);
                        key.Clear();
                        value.Clear();
                    }
                }
            }
            catch (Exception e)
            {
                error = e.ToString();
            }
        }

        private int findEnd(string json, int start)
        {
            int num = 0;
            while(start < json.Length)
            {
                char c = json[start++];
                char c2 = json[start];
                if(c == '\"' && num == 0)
                {
                    num++;
                }
                else if(c == '\"' && num == 1)
                {
                    return start - 1;
                }
                else if(c == '\\' && c2 == '\"')
                {
                    start++;
                }
            }
            return 0;
        }
        public void handleArray(string json)
        {
            int i = 0;
            int length = json.Length;
            while (i < length)
            {
                while (i < length && json[i++] != '{') ;
                value.Append("{");
                while (
                    (i < length && json[i] != '}' && isStart == false) ||
                    (i < length && json[i] == '}' && isStart == false && big != 0) ||
                    (i < length && isStart))
                {
                    if (json[i] == '"' && isStart == false)
                        isStart = true;
                    else if (json[i] == '"' && isStart && json[i - 1] != '\\')
                        isStart = false;

                    if (isStart == false && json[i] == '{')
                        big++;
                    if (isStart == false && json[i] == '}')
                        big--;
                    value.Append(json[i++]);
                }
                value.Append("}");
                if (i >= length)
                {
                    value.Clear();
                    return;
                }
                array.Add(new AnalyzeJson(value.ToString()));
                value.Clear();
            }
        }

        public AnalyzeJson(string value, bool isValue)
        {
            if (isValue)
                val = value;
            else
            {
                val = "";
                error = value;
            }
        }

        public AnalyzeJson this[int index]
        {
            get
            {
                if (error != null)
                    return new AnalyzeJson(error, false);
                else if (array.Count <= index)
                    return new AnalyzeJson("##不存在的下標:" + index + "##", false);
                else if (array[index] == null)
                    return new AnalyzeJson(null);
                else
                    return array[index];
            }
        }
        public AnalyzeJson this[string key]
        {
            get
            {
                if (error != null)
                    return new AnalyzeJson(error, false);
                else if (dic.ContainsKey(key) == false)
                    return new AnalyzeJson("##不存在的鍵:" + key + "##", false);
                else if (dic[key] == null)
                    return new AnalyzeJson(null);
                else
                    return dic[key];
            }

        }
        public int getArrayCount()
        {
            return array.Count;
        }

        public override string ToString()
        {
            if (error != null)
                return error;
            return val;
        }
    }

 

 

//======================================

111.txt內容:

{"RequestData":"{\"ErrMessage\":null,\"IsOk\":true,\"UserID\":\"90660C73-8CA4-4596-85E2-C23F2AF67F51\"}","SessionId":"0e52aa30-a659-45a7-a49d-f32608a09f7e","Sign":"DCC4A8818A39DFC9CFE1BA424E8AA6B1","TequestType":"MocLogin","TimeStamp":"2019-07-12 07:24:48"}@@

示例:

AnalyzeJson analyzeJson = new AnalyzeJson(File.ReadAllText("111.txt", Encoding.Default));

string val = analyzeJson["RequestData"].Tostring();

 

如有問題,可以留言-_-

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章