一、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(); }