1 using System.Collections.Generic; 2 using Newtonsoft.Json.Linq; 3 using Newtonsoft.Json; 4 using System.Web.Script.Serialization; 5 6 7 //使用JavaScriptSerializer()方式转json,需要添加System.Web.Extensions.dll最低的frameword3.5版本才有该dll 8 //使用JsonConvert方式需要Newtonsoft.dll;引用Newtonsoft.Json,frameword2.0也可以用 9 //字符串转json 10 public static void strJson() 11 { 12 string jsonText = "{"shenzheng":"深圳","beijing":"北京","shanghai":[{"zj1":"zj11","zj2":"zj22"},"zjs"]}"; 13 //转为json对象 14 JObject jo = (JObject)JsonConvert.DeserializeObject(jsonText); 15 string zone = jo["shenzheng"].ToString();//输出 深圳 16 string zone_en = jo["shanghai"].ToString();//"[ { "zj1": "zj11", "zj2": "zj22" }, "zjs" ]" 17 string zj1 = jo["shanghai"][1].ToString();//"zjs" 18 Console.WriteLine(jo); 19 } 20 //JsonConvert方式的集合转json 21 string jo =JsonConvert.SerializeObject(ListUserInfoModel); 22 23 24 25 26 //对象与数组转JSON 27 public static void GetJsonString() 28 { 29 //初始化对象 30 Obj product = new Obj() { Name = "苹果", Price = 5.5 }; 31 //序列化 32 string o = new JavaScriptSerializer().Serialize(product);//值:"{"Name":"苹果","Price":5.5}" 33 34 35 36 //数组转json 37 List<Obj> products = new List<Obj>(){ 38 new Obj(){Name="苹果",Price=5.5}, 39 new Obj(){Name="橘子",Price=2.5}, 40 new Obj(){Name="干柿子",Price=16.00} 41 }; 42 43 ProductList productlist = new ProductList(); 44 productlist.GetProducts = products; 45 //序列化 46 string os = new JavaScriptSerializer().Serialize(productlist); 47 //输出 "{"GetProducts":[{"Name":"苹果","Price":5.5},{"Name":"橘子","Price":2.5},{"Name":"干柿子","Price":16}]}" 48 } 49 50 51 52 53 //json转对象、数组, 反序列化 54 public static void JSONStringToList() 55 { 56 57 //json格式字符串 58 string JsonStr = "{Name:'苹果',Price:5.5}"; 59 JavaScriptSerializer Serializer = new JavaScriptSerializer(); 60 61 //json字符串转为对象, 反序列化 62 Obj obj = Serializer.Deserialize<Obj>(JsonStr); 63 Console.Write(obj.Name + ":" + obj.Price + " "); 64 65 66 67 //json格式字符串 68 string JsonStrs = "[{Name:'苹果',Price:5.5},{Name:'橘子',Price:2.5},{Name:'柿子',Price:16}]"; 69 70 JavaScriptSerializer Serializers = new JavaScriptSerializer(); 71 72 //json字符串转为数组对象, 反序列化 73 List<Obj> objs = Serializers.Deserialize<List<Obj>>(JsonStrs); 74 75 foreach (var item in objs) 76 { 77 Console.Write(item.Name + ":" + item.Price + " "); 78 } 79 }
https://blog.csdn.net/yh12346789/article/details/78768334