C# 序列化與反序列化json

liuxixi發表於2017-06-16

與合作伙伴討論問題,說到的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 }

 

相關文章