添加引用:
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
操作json字符串方法
/// <summary> /// linq操作json /// </summary> public void OpearteJson() { string jsonStr = "{\"name\":\"小明\",\"age\":\"20\",\"phone\":[{\"type\":\"phone\"},{\"type\":\"huawei\"}]}"; var jsonObject = JObject.Parse(jsonStr); var name = jsonObject["name"].ToString();//根据对象key获取value var phoneArr = jsonObject["phone"] as JArray;//获取数组key键的值 foreach (JObject item in phoneArr)//遍历json对象数组 { foreach (var keyValue in item)//循环遍历json对象键值对 { var key = keyValue.Key; var value = keyValue.Value.ToString(); } } }
遍历json字符串的key value值:
/// <summary> /// 获取json字符串的键值对,不包含数组json /// </summary> /// <param name="jsonStr">json字符串,例如:"{\"name\":\"szl\",\"age\":\"20\"}"</param> /// <returns></returns> public Dictionary<string, List<string>> GetJsonKeyValue(string jsonStr) { JObject jsonObj = JObject.Parse(jsonStr);//将json字符串转换成json对象 Dictionary<string, List<string>> result = new Dictionary<string, List<string>>(); List<string> key = new List<string>(); List<string> value = new List<string>(); foreach (var item in jsonObj)//遍历json对象的所有键值对 { key.Add(item.Key); value.Add(item.Value.ToString()); } result.Add("key", key); result.Add("value", value); return result; }