首页 > 编程语言 > 详细

c#操作json 使用JavaScriptSerializer

时间:2017-04-18 17:27:24      阅读:348      评论:0      收藏:0      [点我收藏+]

需要引用: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

原文:http://www.cnblogs.com/yaosj/p/6728907.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!