一、Json字符串转换为Dictionary

        /// <summary>
        /// JSON字符串转为  Dictionary
       /// </summary>
       /// <typeparam name="TKey"></typeparam>
       /// <typeparam name="TValue"></typeparam>
       /// <param name="jsonStr"></param>
       /// <returns></returns>
        public static Dictionary<string, string> DeserializeStringToDictionary<TKey, TValue>(string jsonStr)
        {
            if (string.IsNullOrEmpty(jsonStr))
                return new Dictionary<string, string>();

            Dictionary<string, string> jsonDict = JsonConvert.DeserializeObject<Dictionary<string, string>>(jsonStr);
                            
            return jsonDict;

        }

二、解析json

JObject解析单个Json;

JArray(解析匿名Json数组);

JsonConvert.DeserializeObject(反序列化json)

      ①添加using Newtonsoft.Json.Linq引用

      ②相关方法

  •         遍历json对象(解析单个json)      
               var josn = new { ID = "11", Name = "Test", Sex = "" };
                string strJson = JsonConvert.SerializeObject(josn);
                JObject jsonObj = JObject.Parse(strJson);
                string strID=jsonObj["ID"].ToString().Trim();
  • 数组类型的json对象
              var v1 = new { ID = "11", Name = "T1", Sex = "" };
                var v2 = new { ID = "22", Name = "T2", Sex = "" };
                var josn = new { v1, v2 };
                string strJosn = JsonConvert.SerializeObject(josn);
                JArray ja = JArray.Parse(strJosn);
                for (int i = 0; i < ja.Count; i++)
                {
                    JObject jsonOB = JObject.Parse(ja[i].ToString().Trim());
                    string strID = jsonOB["ID"].ToString().Trim();
                }

 

posted on 2020-12-18 11:09  梦想&现实  阅读(188)  评论(0编辑  收藏  举报