首页 > 代码库 > Json序列化与反序列化

Json序列化与反序列化

参考:http://www.cnblogs.com/caofangsheng/p/5687994.html#commentform

下载链接:http://download.csdn.net/detail/u010312811/9682971

效果图如下:

技术分享

 

Json可以很好的用于数据结构,将数据序列化或反序列化,进而方便数据的传递(暂时只用过这么点功能。。。)

具体步骤如下:

(1)添加“Json”引用,步骤完成之后,“引用”中出现“Newtonsoft.Json”

技术分享

技术分享

 

(2)添加命名空间

1    using Newtonsoft.Json;
2    using Newtonsoft.Json.Linq;

(3)自定义类StudentInfo

 1    public string Name
 2    {
 3        get { return _name; }
 4        set { _name = value; }
 5    }
 6    public int Age
 7    {
 8        get { return _age; }
 9        set { _age = value; }
10    }
11    public bool Sex
12    {
13        get { return _sex; }
14        set { _sex = value; }
15    }

(4)序列化:

1   StudentInfo info = new StudentInfo();
2   info.Name = txtName.Text;
3   info.Age = int.Parse(txtAge.Text);
4   info.Sex = comboBox1.Text == "" ? true : false;
5             
6   string jsonData = http://www.mamicode.com/JsonConvert.SerializeObject(info) + "\r\n";
7   txtContent.Text += jsonData;

(5)反序列化

1   string json = txtContent.Text;
2   StudentInfo info = JsonConvert.DeserializeObject<StudentInfo>(json);
3   txtName.Text = info.Name;
4   txtAge.Text = info.Age.ToString();
5   comboBox1.Text = info.Sex ? "" : "";

 

Json序列化与反序列化