主頁 > .NET開發 > C#物件與Json互轉

C#物件與Json互轉

2020-09-12 02:32:45 .NET開發

 

使用基礎類

using System;
using System.Collections.Generic;

namespace JSON
{
    /// <summary>
    /// 拓展Linq
    /// </summary>
    public static class TLinq
    {
        /// <summary>
        /// 跳過指定的數量的序列中的元素,然后回傳剩余元素
        /// </summary>
        /// <typeparam name="T">資料型別</typeparam>
        /// <param name="arr">原陣列</param>
        /// <param name="skipCount">跳過的長度</param>
        /// <returns></returns>
        public static T[] Skip<T>(this T[] arr, int skipCount)
        {
            if (arr.Length > skipCount)
            {
                T[] res = new T[arr.Length - skipCount];
                int num = 0;
                for (int i = skipCount; i < arr.Length; i++)
                {
                    res[num] = arr[i];
                    num++;
                }
                return res;
            }
            else
            {
                throw new ArgumentException("skipCount大于arr長度");
            }
        }
        /// <summary>
        /// 回傳此陣列的指定長度
        /// </summary>
        /// <typeparam name="T">資料型別</typeparam>
        /// <param name="arr">原陣列</param>
        /// <param name="length">指定長度</param>
        /// <returns></returns>
        public static T[] Take<T>(this T[] arr, int length)
        {
            if (length < arr.Length)
            {
                T[] res = new T[length];
                for (int i = 0; i < length; i++)
                {
                    res[i] = arr[i];
                }
                return res;
            }
            else
            {
                throw new ArgumentException("length大于arr長度");
            }
        }
        /// <summary>
        /// 反轉元素
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="arr"></param>
        /// <returns></returns>
        public static T[] Reverse<T>(this T[] arr)
        {
            List<T> list = new List<T>();
            for (int i = arr.Length - 1; i >= 0; i--)
            {
                list.Add(arr[i]);
            }
            return list.ToArray();
        }
        /// <summary>
        /// 分割一次,從尾開始,回傳剩余
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="arr"></param>
        /// <param name="last"></param>
        /// <param name="split"></param>
        /// <returns>回傳剩余</returns>
        public static T[] SplitLast<T>(this T[] arr, out T[] last, params T[] split)
        {
            List<T> list = new List<T>();
            int count = 0;
            if (null != split && split.Length > 0)
            {
                for (int i = arr.Length - 1; i >= 0; i--)
                {
                    if (arr[i].Equals(split[split.Length - 1 - count]))
                    {
                        count++;
                        if (count == split.Length)
                        {
                            last = Reverse(list.ToArray());
                            return arr.Take(arr.Length - (arr.Length - i));
                        }
                    }
                    else
                    {
                        if (i < arr.Length - 1 && count > 0)
                        {
                            list.Add(arr[i + 1]);
                        }
                        list.Add(arr[i]);
                        count = 0;
                    }
                }
            }
            last = default;
            return default;
        }
        /// <summary>
        /// 分割一次,從首開始,回傳剩余
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="arr"></param>
        /// <param name="first"></param>
        /// <param name="split"></param>
        /// <returns>回傳剩余</returns>
        public static T[] SplitFirst<T>(this T[] arr, out T[] first, params T[] split)
        {
            first = default;
            List<T> list = new List<T>();
            int count = 0;
            if (null != split && split.Length > 0)
            {
                for (int i = 0; i < arr.Length; i++)
                {
                    if (arr[i].Equals(split[count]))
                    {
                        count++;
                        if (count == split.Length)
                        {
                            first = list.ToArray();
                            return i < arr.Length - 1 ? arr.Skip(i + 1) : default;
                        }
                    }
                    else
                    {
                        if (i > 0 && count > 0)
                        {
                            list.Add(arr[i - 1]);
                        }
                        list.Add(arr[i]);
                        count = 0;
                    }
                }
            }
            return default;
        }

        /// <summary>
        /// 查看陣列是否包含此欄位
        /// </summary>
        /// <typeparam name="T">陣列型別</typeparam>
        /// <param name="arr">陣列實體</param>
        /// <param name="any">比較方法</param>
        /// <returns></returns>
        public static bool Any<T>(this T[] arr, TLinq<T, bool> any)
        {
            foreach (var obj in arr) if (any(obj)) return true;

            return false;
        }
        /// <summary>
        /// 獲取相同數
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="arr"></param>
        /// <param name="same"></param>
        /// <returns></returns>
        public static int Same<T>(this T[] arr, TLinq<T, bool> same)
        {
            int resNum = 0;
            foreach (var obj in arr) if (same(obj)) resNum++;
            return resNum;
        }
        /// <summary>
        /// 頭相同個數
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="arr"></param>
        /// <param name="same"></param>
        /// <returns></returns>
        public static int SameHead<T>(this T[] arr, TLinq<T, bool> same)
        {
            int resNum = 0;
            foreach (var obj in arr)
            {
                if (same(obj))
                {
                    resNum++;
                    continue;
                }
                else
                {
                    break;
                }
            }
            return resNum;
        }
        /// <summary>
        /// 尾相同個數
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="arr"></param>
        /// <param name="same"></param>
        /// <returns></returns>
        public static int SameTail<T>(this T[] arr, TLinq<T, bool> same)
        {
            int resNum = 0;
            for (int i = arr.Length - 1; i >= 0; i--)
            {
                if (same(arr[i]))
                {
                    resNum++;
                    continue;
                }
                else
                {
                    break;
                }
            }
            return resNum;
        }
    }
    /// <summary>
    /// 拓展Linq
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <typeparam name="T1"></typeparam>
    /// <param name="obj">引數物件</param>
    /// <returns></returns>
    public delegate T1 TLinq<in T, out T1>(T obj);
}

物件轉Json

using System;
using System.Collections;
using System.Reflection;
using System.Text;

namespace JSON
{
    /// <summary>
    /// 模型轉為JSON
    /// </summary>
    public static class ToJsonEx
    {
        /// <summary>
        /// 物件轉換為Json
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="ignores">忽略輸出的屬性(不區分大小寫)</param>
        /// <returns></returns>
        public static string ToJson(this Object obj, params string[] ignores)
        {
            return ToJson(obj, false, ignores);
        }
        /// <summary>
        /// 轉換為全部屬性值是字串的Json
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="ignores">忽略輸出的屬性(不區分大小寫)</param>
        /// <returns></returns>
        public static string ToAllStringJson(this Object obj, params string[] ignores)
        {
            return ToJson(obj, true, ignores);
        }

        /// <summary>
        /// 物件轉換為Json
        /// </summary>
        /// <param name="obj">物件實體</param>
        /// <param name="isStr">是否全部輸出為字串</param>
        /// <param name="ignores">忽略輸出的屬性(不區分大小寫)</param>
        /// <returns>Json字串</returns>
        public static string ToJson(this Object obj, bool isStr = false, params string[] ignores)
        {
            switch (obj)
            {
                //TODO:特殊型別轉換添加到此處
                case Guid value:
                    return $"\"{value.ToString()}\"";
                case IList value:
                    return IListToJson(value, isStr, ignores);
                case IDictionary value:
                    return IDictionaryToJson(value, isStr, ignores);
                case Object value:
                    return ObjectToJson(obj, isStr, ignores);
                default:
                    throw new NotImplementedException("無法識別物件!");
            }
        }
        #region 基礎轉換

        /// <summary>
        /// 轉換值為Json字串
        /// </summary>
        /// <param name="value"></param>
        /// <param name="isStr">是否轉為字串</param>
        /// <param name="ignores">忽略欄位</param>
        /// <returns></returns>
        private static string ValueToJson(this object value, bool isStr = false, params string[] ignores)
        {
            if (null == value) return "null";
            string str_property = string.Empty;
            var type = value.GetType();
            switch (type.BaseType.Name)
            {
                case "ValueType":
                case "Object":
                    //獲取此屬性型別標識
                    TypeCode code = Convert.GetTypeCode(value);
                    switch (code)
                    {
                        case TypeCode.Empty:
                            str_property += "null";
                            break;
                        case TypeCode.Object:
                            str_property += ToJson(value, isStr, ignores);
                            break;
                        case TypeCode.Boolean:
                            str_property += isStr ? $"\"{value.ToString().ToLower()}\"" : value.ToString().ToLower();
                            break;
                        case TypeCode.Int32:
                        case TypeCode.SByte:
                        case TypeCode.Byte:
                        case TypeCode.Int16:
                        case TypeCode.UInt16:
                        case TypeCode.UInt32:
                        case TypeCode.Int64:
                        case TypeCode.UInt64:
                        case TypeCode.Single:
                        case TypeCode.Double:
                        case TypeCode.Decimal:
                            str_property += isStr ? $"\"{value}\"" : value;
                            break;
                        case TypeCode.Char:
                            str_property += $"\"{(((Char)value != Char.MinValue) ? value : string.Empty)}\"";
                            break;
                        case TypeCode.String:
                            str_property += $"\"{(((String)value != String.Empty) ? value : string.Empty)}\"";
                            break;
                        case TypeCode.DateTime:
                            str_property += $"\"{Convert.ToDateTime(value).ToString("yyyy-MM-dd HH:mm:ss")}\"";
                            break;
                        case TypeCode.DBNull:
                        default:
                            throw new NotImplementedException("無法識別物件!");
                    }
                    break;
                case "Enum":
                    str_property += isStr ? $"\"{value.GetHashCode()}\"" : value.GetHashCode().ToString();
                    break;
                default:
                    str_property += ToJson(value, isStr, ignores);
                    break;
            }


            return str_property;
        }
        /// <summary>
        /// 物件轉換為Json
        /// </summary>
        /// <param name="obj">物件實體</param>
        /// <param name="isStr"></param>
        /// <param name="ignores">忽略輸出的屬性</param>
        /// <returns>Json字串</returns>
        private static string ObjectToJson(this Object obj, bool isStr = false, params string[] ignores)
        {
            PropertyInfo[] properties = obj.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
            //Object 頭
            StringBuilder builder = new StringBuilder("{");

            foreach (var property in properties)
            {
                if (null != ignores && ignores.Length > 0 && ignores.Any(g => g.ToLower() == property.Name.ToLower()))
                {
                    continue;
                }
                else
                {
                    //此屬性json表示字符
                    string str_property = string.Empty;
                    //屬性名稱格式
                    str_property = $"\"{property.Name}\":";
                    //獲取此屬性值
                    Object value =https://www.cnblogs.com/Jzs001/p/ property.GetValue(obj);
                    //添加此屬性值
                    str_property += ValueToJson(value, isStr, ignores);
                    //是否添加間隔符
                    builder.Append(str_property + ',');
                }
            }
            //有內容時去除多余間隔符
            if (properties.Length > 0 && builder.Length > 1)
            {
                //去除多余間隔符
                builder.Remove(builder.Length - 1, 1);
            }
            //Object 尾
            builder.Append("}");
            return builder.ToString();
        }
        /// <summary>
        /// 組型別轉換為Json
        /// </summary>
        /// <param name="list">組型別</param>
        /// <param name="isStr"></param>
        /// <param name="ignores">忽略輸出的屬性</param>
        /// <returns>Json字串</returns>
        private static string IListToJson(this IList list, bool isStr = false, params string[] ignores)
        {
            StringBuilder builder = new StringBuilder("[");
            //轉換值為json字串
            foreach (var value in list) builder.Append(ValueToJson(value, isStr, ignores) + ',');
            //有內容時去除多余間隔符
            if (list.Count > 0)
            {
                //去除多余間隔符
                builder.Remove(builder.Length - 1, 1);
            }
            //添加結尾符
            builder.Append("]");
            return builder.ToString();
        }
        /// <summary>
        /// 字典型別轉換為Json字串
        /// </summary>
        /// <param name="dictionary"></param>
        /// <param name="isStr"></param>
        /// <param name="ignores"></param>
        /// <returns>Json字串</returns>
        private static string IDictionaryToJson(this IDictionary dictionary, bool isStr = false, params string[] ignores)
        {
            StringBuilder builder = new StringBuilder("[");
            foreach (var key in dictionary.Keys)
            {
                var value =https://www.cnblogs.com/Jzs001/p/ dictionary[key];
                //外邊界
                builder.Append("[");
                //轉換key
                builder.Append(ValueToJson(key, isStr, ignores));
                //分隔
                builder.Append(",");
                //轉換value
                builder.Append(ValueToJson(value, isStr, ignores));
                //尾邊界
                builder.Append("],");
            }
            //有內容時去除多余間隔符
            if (dictionary.Count > 0)
            {
                //去除多余間隔符
                builder.Remove(builder.Length - 1, 1);
            }
            builder.Append("]");
            return builder.ToString();
        }
        #endregion
    }

}

Json轉物件

using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;

namespace JSON
{
    /* Json轉obj
     * 得到轉換型別
     * 決議Json,決議為此物件一個屬性跟一個此屬性的字串,為object時,回圈決議(object)
     * 
     * 
     */

    /// <summary>
    /// Json轉化為Object
    /// </summary>
    public static class ToObjectEX
    {
        /*
         * Object Json: {key:value}  [value,value]  [[key,value],[key,value]]  value
         */
        /// <summary>
        /// 轉換Json為指定型別
        /// </summary>
        /// <typeparam name="T">物件型別</typeparam>
        /// <param name="objectJson">Object的Json字串</param>
        /// <returns>指定型別實體</returns>
        public static T ToObject<T>(string objectJson)
        {
            return (T)ToObject(typeof(T), objectJson);
        }

        /*
         * Object Json: {key:value}  [value,value]  [[key,value],[key,value]]  value
         */
        /// <summary>
        /// 轉換Json為指定型別
        /// </summary>
        /// <param name="type">物件型別</param>
        /// <param name="objectJson">Object的Json字串</param>
        /// <returns>指定型別實體</returns>
        public static object ToObject(Type type, string objectJson)
        {
            switch (type.Name)
            {
                case "Object": //TODO:無法決議型別為Object的實體[默認轉為字串]
                    return objectJson;
                case "Guid":
                    return new Guid(objectJson.Trim('"'));
                case "List`1":
                    return JsonToIList(type, objectJson);
                case "Dictionary`2":
                    return JsonToIDictionary(type, objectJson);
                default:
                    if (type.BaseType.Name == "Array")
                    {
                        return JsonToArray(type, objectJson);
                    }
                    else
                    {
                        return JsonToObject(type, objectJson);
                    }
            }
        }

        #region 基礎轉換

        /*
         * Value Json: value
         */
        /// <summary>
        /// 轉換Json為指定型別值
        /// </summary>
        /// <param name="type">物件型別</param>
        /// <param name="valueJson">值的Json字串</param>
        /// <returns>指定型別實體</returns>
        private static object JsonToValue(Type type, string valueJson)
        {
            if ("null" != valueJson)
            {
                valueJson = RemoveSE(valueJson);
                //此屬性的型別
                TypeCode typeCode = Type.GetTypeCode(type);
                switch (typeCode)
                {
                    case TypeCode.Object:
                        return ToObject(type, valueJson);
                    case TypeCode.Char:
                        if (string.IsNullOrEmpty(valueJson))
                        {
                            return Char.MinValue;
                        }
                        goto case TypeCode.Single;
                    case TypeCode.String:
                        if (string.IsNullOrEmpty(valueJson))
                        {
                            return string.Empty;
                        }
                        goto case TypeCode.Single;
                    case TypeCode.DateTime:
                    case TypeCode.Boolean:
                    case TypeCode.Int32:
                    case TypeCode.SByte:
                    case TypeCode.Byte:
                    case TypeCode.Int16:
                    case TypeCode.UInt16:
                    case TypeCode.UInt32:
                    case TypeCode.Int64:
                    case TypeCode.UInt64:
                    case TypeCode.Double:
                    case TypeCode.Decimal:
                    case TypeCode.Single:
                        if (!string.IsNullOrEmpty(valueJson))
                        {
                            return Convert.ChangeType(valueJson, typeCode);
                        }
                        break;
                    case TypeCode.Empty:
                    case TypeCode.DBNull:
                    default:
                        throw new NotImplementedException("未知型別");
                }
            }
            return default;
        }

        /*
         * Object Json: {key:value}
         */
        /// <summary>
        /// 轉換Json為指定型別
        /// </summary>
        /// <param name="type">物件型別</param>
        /// <param name="objectJson">Json字串</param>
        /// <returns>指定型別實體</returns>
        private static object JsonToObject(Type type, string objectJson)
        {
            //創建此型別實體
            var obj = Activator.CreateInstance(type);
            //獲取物件型別
            PropertyInfo[] properties = obj.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
            //決議ObjectJson
            Dictionary<string, string> pairs = ParsingObjectJson(objectJson);
            //屬性不為空 和 決議字串不為空
            if (properties.Length > 0 && pairs.Count > 0)
            {
                //此物件的所有屬性
                foreach (var property in properties)
                {
                    //Json是否有此屬性
                    if (pairs.ContainsKey(property.Name))
                    {
                        //沒有此屬性 或 Value為空 跳過
                        if (!pairs.ContainsKey(property.Name) || string.IsNullOrEmpty(pairs[property.Name])) continue;
                        //轉換value為型別屬性值
                        property.SetValue(obj, JsonToValue(property.PropertyType, pairs[property.Name]));
                    }
                }
            }
            else
            {
                obj = default;
            }
            return obj;
        }

        /*
         * List Json: [value,value]
         */
        /// <summary>
        /// 轉換Json為指定型別組
        /// </summary>
        /// <param name="type">物件型別</param>
        /// <param name="ilistJson">List的Json字串</param>
        /// <returns>指定型別組實體</returns>
        private static object JsonToIList(Type type, string ilistJson)
        {
            if (!string.IsNullOrEmpty(ilistJson) && ilistJson != "[]" && ilistJson != "null")
            {
                //初始化此IList
                var ilist = (IList)Activator.CreateInstance(type);
                //獲取此實體的物件
                var tempType = type.GenericTypeArguments[0];
                //決議
                List<string> list = ParsingIListJson(ilistJson);
                if (list.Count > 0)
                {
                    foreach (var value in list)
                    {
                        ilist.Add(JsonToValue(tempType, value));
                    }
                    return ilist;
                }
            }
            return default;
        }

        /*
         * Array Json: [value,value]
         */
        /// <summary>
        /// 轉換Json為指定型別組
        /// </summary>
        /// <param name="type">物件型別</param>
        /// <param name="arrayJson">Array的Json字串</param>
        /// <returns>指定型別組實體</returns>
        private static object JsonToArray(Type type, string arrayJson)
        {
            if (!string.IsNullOrEmpty(arrayJson) && arrayJson != "[]" && arrayJson != "null")
            {
                //獲取程式集資訊(除型別外)
                string aqn = new string(type.AssemblyQualifiedName.ToCharArray().SplitFirst(out char[] first, type.FullName.ToCharArray()));
                //獲取陣列維度
                int num = type.Name.ToCharArray().Same(c => c == ']');
                //獲取陣列型別
                type.Name.ToCharArray().SplitFirst(out char[] arrType, '[', ']');
                //陣列型別名稱
                String typeName = new String(arrType);
                //恢復維度
                for (int i = 0; i < num - 1; i++)
                {
                    typeName += "[]";
                }
                //初始化陣列型別
                Type objType = Type.GetType(type.Namespace + '.' + typeName + aqn);
                //決議陣列
                List<string> list = ParsingIListJson(arrayJson);
                //創建陣列,按回傳值長度創建
                var iArr = Array.CreateInstance(objType, list.Count);
                //轉換為陣列值
                for (int i = 0; i < list.Count; i++)
                {
                    iArr.SetValue(JsonToValue(objType, list[i]), i);
                }
                return iArr;
            }
            return default;
        }

        /*
         * 鍵值對 Json: [[key,value],[key,value]]
         */
        /// <summary>
        /// 轉換Json為指定型別鍵值對
        /// </summary>
        /// <param name="type">物件型別</param>
        /// <param name="idictionaryJson">鍵值對的Json字串</param>
        /// <returns>指定型別鍵值對實體</returns>
        private static object JsonToIDictionary(Type type, string idictionaryJson)
        {
            if (!string.IsNullOrEmpty(idictionaryJson) && idictionaryJson != "[]" && idictionaryJson != "null")
            {
                //Key 型別
                Type keyType = type.GenericTypeArguments[0];
                //Value 型別
                Type valueType = type.GenericTypeArguments[1];
                //初始化一個此型別實體
                var dic = (IDictionary)Activator.CreateInstance(type);
                //決議鍵值對json
                Dictionary<string, string> pairs = ParsingIDictionaryJson(idictionaryJson);
                //鍵值對賦值
                foreach (var keyValue in pairs)
                {
                    dic.Add(JsonToValue(keyType, keyValue.Key), JsonToValue(valueType, keyValue.Value));
                }
                return dic;
            }
            return default;
        }
        #endregion

        #region Core
        /// <summary>
        /// 決議ObjectJson為鍵值對(Ok-2020年7月3日18點37分)[Core]
        /// </summary>
        /// <param name="objectJson">實體Json</param>
        /// <returns>實體的屬性與值鍵值對</returns>
        private static Dictionary<string, string> ParsingObjectJson(string objectJson)
        {
            Dictionary<string, string> pairs = new Dictionary<string, string>();
            if (objectJson != "{}" && objectJson != "null")
            {
                string[] jsonArr = objectJson.Split(new string[] { "\":" }, StringSplitOptions.RemoveEmptyEntries);
                if (null != jsonArr && jsonArr.Length > 0)
                {
                    int signLen = -1; //標志長度

                    string key = string.Empty, //key
                        value = https://www.cnblogs.com/Jzs001/p/string.Empty; //value

                    foreach (var str in jsonArr)
                    {
                        signLen += GetSameHead(str);
                        signLen -= GetSameTail(str);

                        //獲取key value
                        char[] resTempValue = https://www.cnblogs.com/Jzs001/p/str.ToCharArray().SplitLast(out char[] resTempKey, ',', '\"');
                        if (null != resTempValue && null != resTempKey)
                        {
                            if (signLen == 0)
                            {
                                pairs[key] += new string(resTempValue);

                                key = new string(resTempKey);
                                pairs.Add(key, string.Empty);
                            }
                            else
                            {
                                pairs[key] += str + "\":";
                            }
                        }
                        else
                        {
                            if (pairs.Count > 0)
                            {
                                pairs[key] += str + "\":";
                            }
                            else
                            {
                                str.ToCharArray().SplitLast(out char[] last, '{', '\"');
                                key = new String(last);
                                pairs.Add(key, string.Empty);
                            }
                        }
                    }
                    if (pairs.Count >= 1)
                    {
                        //清除最后一次添加的 \": 
                        pairs[key] = pairs[key].Remove(pairs[key].Length - 3);
                    }
                }
            }
            return pairs;
        }

        /*
         * IList Json: [value,value]  [[value,value],[value,value]]  [[[value,value],[value,value]],[[value,value]]]
         */
        /// <summary>
        /// 決議IListJson為組,支持多維陣列(分割成單個實體Json,Ok 2020年7月4日15點01分)[Core]
        /// </summary>
        /// <param name="ilistJson">組Json</param>
        /// <returns>決議后的值組</returns>
        private static List<string> ParsingIListJson(string ilistJson)
        {
            List<string> list = new List<string>();
            int signLen = 0; //標志長度

            //去除頭尾
            string temp = ilistJson.Remove(0, 1);
            temp = temp.Remove(temp.Length - 1, 1);

            string[] arr = temp.Split(',');
            string value = https://www.cnblogs.com/Jzs001/p/string.Empty;
            foreach (var str in arr)
            {
                signLen += GetSameHead(str);
                signLen -= GetSameTail(str);
                value += str;
                if (signLen == 0)
                {
                    list.Add(value);
                    value = string.Empty;
                }
                else
                {
                    value += ',';
                }
            }
            return list;
        }

        /*
         * 鍵值對 Json: [[key,value],[key,value]]
         */
        /// <summary>
        /// 決議IDictionaryJson為鍵值對
        /// </summary>
        /// <param name="idictionaryJson">鍵值對Json</param>
        /// <returns>決議后的鍵值對</returns>
        private static Dictionary<string, string> ParsingIDictionaryJson(string idictionaryJson)
        {
            Dictionary<string, string> pairs = new Dictionary<string, string>();
            var arr = ParsingIListJson(idictionaryJson);

            foreach (var item in arr)
            {
                var tempArr = ParsingIListJson(item);
                if (tempArr.Count == 2)
                {
                    pairs.Add(tempArr[0], tempArr[1]);
                }
                else
                {
                    pairs.Add(tempArr[0], string.Empty);
                }
            }

            return pairs;
        }

        /// <summary>
        /// 獲取相同頭數量
        /// </summary>
        /// <param name="jsonValue"></param>
        /// <returns></returns>
        private static int GetSameHead(string jsonValue)
        {
            int resNum = 0;
            resNum += jsonValue.ToCharArray().Same(c => c == '{');
            resNum += jsonValue.ToCharArray().Same(c => c == '[');
            return resNum;
        }

        /// <summary>
        /// 獲取相同結尾數量
        /// </summary>
        /// <param name="jsonValue"></param>
        /// <returns></returns>
        private static int GetSameTail(string jsonValue)
        {
            int resNum = 0;
            resNum += jsonValue.ToCharArray().Same(c => c == '}');
            resNum += jsonValue.ToCharArray().Same(c => c == ']');
            return resNum;
        }
        /// <summary>
        /// 洗掉首尾 \" 符
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        private static string RemoveSE(string str)
        {
            if (str.StartsWith("\""))
            {
                str = str.Remove(0, 1);
            }
            if (str.EndsWith("\""))
            {
                str = str.Remove(str.Length - 1, 1);
            }
            return str;
        }
        #endregion
    }
}

 

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/9610.html

標籤:C#

上一篇:C# 實作TXT檔案轉Table

下一篇:C# 9.0 終于來了, Top-level programs 和 Partial Methods 兩大新特性探究

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • WebAPI簡介

    Web體系結構: 有三個核心:資源(resource),URL(統一資源識別符號)和表示 他們的關系是這樣的:一個資源由一個URL進行標識,HTTP客戶端使用URL定位資源,表示是從資源回傳資料,媒體型別是資源回傳的資料格式。 接下來我們說下HTTP. HTTP協議的系統是一種無狀態的方式,使用請求/ ......

    uj5u.com 2020-09-09 22:07:47 more
  • asp.net core 3.1 入口:Program.cs中的Main函式

    本文分析Program.cs 中Main()函式中代碼的運行順序分析asp.net core程式的啟動,重點不是剖析原始碼,而是理清程式開始時執行的順序。到呼叫了哪些實體,哪些法方。asp.net core 3.1 的程式入口在專案Program.cs檔案里,如下。ususing System; us ......

    uj5u.com 2020-09-09 22:07:49 more
  • asp.net網站作為websocket服務端的應用該如何寫

    最近被websocket的一個問題困擾了很久,有一個需求是在web網站中搭建websocket服務。客戶端通過網頁與服務器建立連接,然后服務器根據ip給客戶端網頁發送資訊。 其實,這個需求并不難,只是剛開始對websocket的內容不太了解。上網搜索了一下,有通過asp.net core 實作的、有 ......

    uj5u.com 2020-09-09 22:08:02 more
  • ASP.NET 開源匯入匯出庫Magicodes.IE Docker中使用

    Magicodes.IE在Docker中使用 更新歷史 2019.02.13 【Nuget】版本更新到2.0.2 【匯入】修復單列匯入的Bug,單元測驗“OneColumnImporter_Test”。問題見(https://github.com/dotnetcore/Magicodes.IE/is ......

    uj5u.com 2020-09-09 22:08:05 more
  • 在webform中使用ajax

    如果你用過Asp.net webform, 說明你也算是.NET 開發的老兵了。WEBform應該是2011 2013左右,當時還用visual studio 2005、 visual studio 2008。后來基本都用的是MVC。 如果是新開發的專案,估計沒人會用webform技術。但是有些舊版 ......

    uj5u.com 2020-09-09 22:08:50 more
  • iis添加asp.net網站,訪問提示:由于擴展配置問題而無法提供您請求的

    今天在iis服務器配置asp.net網站,遇到一個問題,記錄一下: 問題:由于擴展配置問題而無法提供您請求的頁面。如果該頁面是腳本,請添加處理程式。如果應下載檔案,請添加 MIME 映射。 WindowServer2012服務器,添加角色安裝完.netframework和iis之后,運行aspx頁面 ......

    uj5u.com 2020-09-09 22:10:00 more
  • WebAPI-處理架構

    帶著問題去思考,大家好! 問題1:HTTP請求和回傳相應的HTTP回應資訊之間發生了什么? 1:首先是最底層,托管層,位于WebAPI和底層HTTP堆疊之間 2:其次是 訊息處理程式管道層,這里比如日志和快取。OWIN的參考是將訊息處理程式管道的一些功能下移到堆疊下端的OWIN中間件了。 3:控制器處理 ......

    uj5u.com 2020-09-09 22:11:13 more
  • 微信門戶開發框架-使用指導說明書

    微信門戶應用管理系統,采用基于 MVC + Bootstrap + Ajax + Enterprise Library的技術路線,界面層采用Boostrap + Metronic組合的前端框架,資料訪問層支持Oracle、SQLServer、MySQL、PostgreSQL等資料庫。框架以MVC5,... ......

    uj5u.com 2020-09-09 22:15:18 more
  • WebAPI-HTTP編程模型

    帶著問題去思考,大家好!它是什么?它包含什么?它能干什么? 訊息 HTTP編程模型的核心就是訊息抽象,表示為:HttPRequestMessage,HttpResponseMessage.用于客戶端和服務端之間交換請求和回應訊息。 HttpMethod類包含了一組靜態屬性: private stat ......

    uj5u.com 2020-09-09 22:15:23 more
  • 部署WebApi隨筆

    一、跨域 NuGet參考Microsoft.AspNet.WebApi.Cors WebApiConfig.cs中配置: // Web API 配置和服務 config.EnableCors(new EnableCorsAttribute("*", "*", "*")); 二、清除默認回傳XML格式 ......

    uj5u.com 2020-09-09 22:15:48 more
最新发布
  • C#多執行緒學習(二) 如何操縱一個執行緒

    <a href="https://www.cnblogs.com/x-zhi/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/2943582/20220801082530.png" alt="" /></...

    uj5u.com 2023-04-19 09:17:20 more
  • C#多執行緒學習(二) 如何操縱一個執行緒

    C#多執行緒學習(二) 如何操縱一個執行緒 執行緒學習第一篇:C#多執行緒學習(一) 多執行緒的相關概念 下面我們就動手來創建一個執行緒,使用Thread類創建執行緒時,只需提供執行緒入口即可。(執行緒入口使程式知道該讓這個執行緒干什么事) 在C#中,執行緒入口是通過ThreadStart代理(delegate)來提供的 ......

    uj5u.com 2023-04-19 09:16:49 more
  • 記一次 .NET某醫療器械清洗系統 卡死分析

    <a href="https://www.cnblogs.com/huangxincheng/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/214741/20200614104537.png" alt="" /&g...

    uj5u.com 2023-04-18 08:39:04 more
  • 記一次 .NET某醫療器械清洗系統 卡死分析

    一:背景 1. 講故事 前段時間協助訓練營里的一位朋友分析了一個程式卡死的問題,回過頭來看這個案例比較經典,這篇稍微整理一下供后來者少踩坑吧。 二:WinDbg 分析 1. 為什么會卡死 因為是表單程式,理所當然就是看主執行緒此時正在做什么? 可以用 ~0s ; k 看一下便知。 0:000> k # ......

    uj5u.com 2023-04-18 08:33:10 more
  • SignalR, No Connection with that ID,IIS

    <a href="https://www.cnblogs.com/smartstar/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/u36196.jpg" alt="" /></a>...

    uj5u.com 2023-03-30 17:21:52 more
  • 一次對pool的誤用導致的.net頻繁gc的診斷分析

    <a href="https://www.cnblogs.com/dotnet-diagnostic/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/3115652/20230225090434.png" alt=""...

    uj5u.com 2023-03-28 10:15:33 more
  • 一次對pool的誤用導致的.net頻繁gc的診斷分析

    <a href="https://www.cnblogs.com/dotnet-diagnostic/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/3115652/20230225090434.png" alt=""...

    uj5u.com 2023-03-28 10:13:31 more
  • C#遍歷指定檔案夾中所有檔案的3種方法

    <a href="https://www.cnblogs.com/xbhp/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/957602/20230310105611.png" alt="" /></a&...

    uj5u.com 2023-03-27 14:46:55 more
  • C#/VB.NET:如何將PDF轉為PDF/A

    <a href="https://www.cnblogs.com/Carina-baby/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/2859233/20220427162558.png" alt="" />...

    uj5u.com 2023-03-27 14:46:35 more
  • 武裝你的WEBAPI-OData聚合查詢

    <a href="https://www.cnblogs.com/podolski/" target="_blank"><img width="48" height="48" class="pfs" src="https://pic.cnblogs.com/face/616093/20140323000327.png" alt="" /><...

    uj5u.com 2023-03-27 14:46:16 more