c#操作json 使用JavaScriptSerializer
需要引用:System.Web.Extensions
/// <summary> /// json的信息。保证定义的变量和json的字段一样(也可以使用struct) /// </summary> public class JsonInfo { public string res_code { get; set; } public string res_info { get; set; } public List<Persion> persionList; } public class Persion { public string name { get; set; } public string age { get; set; } } public class OperateJson { public static void ParseJson() { string json = "{'res_code':'0','res_info':'ok','persionList':[{'name':'ladygaga','age':'50'},{'name':'swift','age':'42'}]}"; JavaScriptSerializer js = new JavaScriptSerializer(); JsonInfo jsonInfo = js.Deserialize<JsonInfo>(json); } public static string CreateJson(object objectList) { JavaScriptSerializer js = new JavaScriptSerializer(); string json = js.Serialize(objectList); return json; } }
使用
private void button3_Click(object sender, EventArgs e) { OperateJson.ParseJson(); } private void button4_Click(object sender, EventArgs e) { JsonInfo jsonInfo = new JsonInfo(); jsonInfo.res_code = "0"; jsonInfo.res_info = "ok"; jsonInfo.persionList = new List<Persion>(); Persion persion = new Persion(); persion.name = "lady gaga"; persion.age = "50"; jsonInfo.persionList.Add(persion); Persion persion1 = new Persion(); persion1.name = "swift"; persion1.age = "42"; jsonInfo.persionList.Add(persion1); OperateJson.CreateJson(jsonInfo); }