Newtonsoft.Json

在.NET环境下面,我们使用Json.net来实现JSON数据的序列化和反序列化。
     首先点击连接http://sourceforge.net/projects/csjson/?source=dlp 下载JSON .NET插件和代码。
     然后在项目中进行引用Newtonsoft.Json.dll
     添加命名空间:using Newtonsoft.Json;
     下面介绍json序列化和反序列化的放个重要方法和例子:
JsonConvert.SerializeObject(object value)序列化,它有个重载方法JsonConvert.SerializeObject(object value, params JsonConverter[] converters)。
JsonConvert.DeserializeObject(string value, Type type),反序列化,它有个重载方法JsonConvert.DeserializeObject(string value, Type type, params JsonConverter[] converters)
这两个方法可以实现基本的序列化和反序列化要求,请看下面的例子:
首先我们先建一个Person类代码如下:
  public class Person
    {
        private string name;
        public string Name
        {
            get { return name; }
            set { name = value; }
        }
        private int age;
        public int Age
        {
            get { return age; }
            set { age = value; }
        }
    }
1)序列化
 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newtonsoft.Json;
 
namespace JSONnet
{
    public partial class test : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Person person = new Person();
            person.Name = "GoldenEasy";
            person.Age = 25;
            string strSerializeJSON = JsonConvert.SerializeObject(person);
            Response.Write(strSerializeJSON);                     
        }
    }
}
输出结果:
{"Name":"GoldenEasy","Age":25}
2)反序列化
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newtonsoft.Json;
 
namespace JSONnet
{
    public partial class test : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Person person = new Person();
            person.Name = "GoldenEasy";
            person.Age = 25;
            string strSerializeJSON = JsonConvert.SerializeObject(person);           
            Person user = (Person)JsonConvert.DeserializeObject(strSerializeJSON, typeof(Person));
            Response.Write(user.Name);
         
        }
    }
}
输出结果为:GoldenEasy
posted @ 2015-01-20 16:22  eaysun  阅读(208)  评论(0编辑  收藏  举报