C# 序列化与反序列化json

与合作伙伴讨论问题,说到的c++与c#数据的转换调用,正好就说到了序列化与反序列化,同样也可用于不同语言间的调用,做了基础示例,作以下整理:

 1 using System.Data;
 2 using System.Drawing;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 using System.Web.Script.Serialization;
 7 using System.Windows.Forms;
 8 
 9 namespace ConsoleApplication1
10 {
11     public partial class Form9 : Form
12     {
13         public Form9()
14         {
15             InitializeComponent();
16             per();
17         }
18         public string GetPersonInfo()
19         {
20             //实例化Person对象
21             Person per = new Person();
22             per.Name = "lxx";
23             per.Age = 28;
24 
25             //Person对象per序列化为json字符串ss
26             JavaScriptSerializer js = new JavaScriptSerializer();
27             string ss = js.Serialize(per);
28             Console.WriteLine(ss);//运行后ss值为:{"Name":"lxx","Age":28}
29             return ss;
30         }
31 
32         /// <summary>
33         /// json字符串ss反序列化为Person对象
34         /// </summary>
35         /// <returns></returns>
36         public Person per()
37         {
38             JavaScriptSerializer js = new JavaScriptSerializer();
39             Person person = js.Deserialize<Person>(GetPersonInfo());
40             return person;
41         }
42     }
43 
44     /// <summary>
45     /// 定义一个可序列化的实体类(也可以为Structure)
46     /// </summary>
47     [Serializable()]
48     public class Person
49     {
50         public string Name { get; set; }
51         public int Age { get; set; }
52     }
53 }

 

posted @ 2017-06-16 15:56  liuxixi  阅读(205)  评论(0编辑  收藏  举报