c#中string字符串转为json与json转对象
添加引用,Newtonsoft.Json.dll
using Newtonsoft.Json.Linq;
1 //字符串转json 2 public static void strJson() 3 { 4 string jsonText = "{"shenzheng":"深圳","beijing":"北京","shanghai":[{"zj1":"zj11","zj2":"zj22"},"zjs"]}"; 5 6 JObject jo = (JObject)JsonConvert.DeserializeObject(jsonText);//或者JObject jo = JObject.Parse(jsonText); 7 string zone = jo["shenzheng"].ToString();//输出 "深圳" 8 string zone_en = jo["shanghai"].ToString();//输出 "[{"zj1":"zj11","zj2":"zj22"},"zjs"]" 9 string zj1 = jo["shanghai"][1].ToString();//输出 "zjs" 10 Console.WriteLine(jo); 11 }
1 //对象与数组转JSON 2 public static void GetJsonString() 3 { 4 //初始化对象 5 Obj product = new Obj() { Name = "苹果", Price = 5.5 }; 6 //序列化 7 string o = new JavaScriptSerializer().Serialize(product);//值:"{\"Name\":\"苹果\",\"Price\":5.5}" 8 9 //数组转json 10 List<Obj> products = new List<Obj>(){ 11 new Obj(){Name="苹果",Price=5.5}, 12 new Obj(){Name="橘子",Price=2.5}, 13 new Obj(){Name="干柿子",Price=16.00} 14 }; 15 16 ProductList productlist = new ProductList(); 17 productlist.GetProducts = products; 18 //序列化 19 string os = new JavaScriptSerializer().Serialize(productlist); 20 //输出 "{\"GetProducts\":[{\"Name\":\"苹果\",\"Price\":5.5},{\"Name\":\"橘子\",\"Price\":2.5},{\"Name\":\"干柿子\",\"Price\":16}]}" 21 } 22 23 //json转对象、数组, 反序列化 24 public static void JSONStringToList() 25 { 26 27 //json格式字符串 28 string JsonStr = "{Name:'苹果',Price:5.5}"; 29 JavaScriptSerializer Serializer = new JavaScriptSerializer(); 30 31 //json字符串转为对象, 反序列化 32 Obj obj = Serializer.Deserialize<Obj>(JsonStr); 33 Console.Write(obj.Name + ":" + obj.Price + "\r\n"); 34 35 //json格式字符串 36 string JsonStrs = "[{Name:'苹果',Price:5.5},{Name:'橘子',Price:2.5},{Name:'柿子',Price:16}]"; 37 38 JavaScriptSerializer Serializers = new JavaScriptSerializer(); 39 40 //json字符串转为数组对象, 反序列化 41 List<Obj> objs = Serializers.Deserialize<List<Obj>>(JsonStrs); 42 43 foreach (var item in objs) 44 { 45 Console.Write(item.Name + ":" + item.Price + "\r\n"); 46 } 47 }