类与json的互相转化(c#)
1 // JavaScriptSerializer需添加dll引用,System.Web.Extensions 2 //Class转json字符串 3 JavaScriptSerializer serializer = new JavaScriptSerializer(); 4 var json = serializer.Serialize(obj); 5 6 //将json字符串在转为原先的类,JsonConvert需添加第三方dll,Newtonsoft.Json.dll 7 var model=JsonConvert.DeserializeObject<ProductModel>(json);
1 string response = "{'name':'jack','age':12 }"; 2 JObject json = JObject.Parse(response);//json字符串转json 3 IEnumerable<JProperty> property = json.Properties();//获取json的所有属性 4 Console.WriteLine(json); 5 foreach (var pro in property) 6 { 7 Console.WriteLine(pro.Name + "-->" + pro.Value);//遍历json属性 8 } 9 10 string arrayStr = "[{'name':'jack','age':12 }]"; 11 JArray jArray = JArray.Parse(arrayStr);//json数组字符串转json数组 12 13 DataTable dt = new DataTable(); 14 dt = JsonConvert.DeserializeObject<DataTable>(jArray.ToString()); 15 16 string jsonStr = JsonConvert.SerializeObject(dt);//表格转json数组字符串 17 Console.WriteLine("1:" + jsonStr); 18 19 string jsonStr2 = JsonConvert.SerializeObject(json);//json转json字符串 20 Console.WriteLine("2:" + jsonStr2); 21 22 string jsonStr3 = JsonConvert.SerializeObject(jArray);//json数组转json数组字符串 23 Console.WriteLine("3:" + jsonStr3);