c#操作json 使用JavaScriptSerializer
Posted 出门遇贵人
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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); }
以上是关于c#操作json 使用JavaScriptSerializer的主要内容,如果未能解决你的问题,请参考以下文章