序列化與反序列化

既来之.则安之發表於2024-05-21
  • 引用DLL

檔案:Newtonsoft.Json.dll
路徑:D:\yonyou\U9CE\Portal\bin\
  • C#實體類

        List<Departments> deptss = new List<Departments>();
        private void Department_Load(object sender, EventArgs e)
        {
            strUri = TexURI.Text;
            strToken = GetToken(TexURI.Text);
            //Department賦值
            deptss.Add(new Departments { OrgCode = "501", DeptCode = "0101", DeptName = "生產部" });
            deptss.Add(new Departments { OrgCode = "501", DeptCode = "0102", DeptName = "製造一課" });
            deptss.Add(new Departments { OrgCode = "501", DeptCode = "0103", DeptName = "製造二課" });
            deptss.Add(new Departments { OrgCode = "501", DeptCode = "0104", DeptName = "製造三課" });
            deptss.Add(new Departments { OrgCode = "501", DeptCode = "0105", DeptName = "製造四課" });
        }

       /// <summary>
        ///部門結構定義
        /// </summary>
        public class Departments
        {
            /// <summary>
            /// 組織編碼
            /// </summary>
            public string OrgCode { get; set; }
            /// <summary>
            /// 部門編碼
            /// </summary>
            public string DeptCode { get; set; }
            /// <summary>
            /// 部門名稱
            /// </summary>
            public string DeptName { get; set; }
        }
  • C#序列化

C#實體資料序列化Json串;

       /// <summary>
        /// 序列化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnJsonX_Click(object sender, EventArgs e)
        {
            TexResult.Text = JsonConvert.SerializeObject(deptss);//SerializeObject序列化物件
        }

  • C#反序列化

根據序列化Json串結果,反序列化Json取值;

        /// <summary>
        /// 反序列化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnJsonF_Click(object sender, EventArgs e)
        {
            List<Departments> Enmity = JsonConvert.DeserializeObject<List<Departments>>(TexResult.Text);//DeserializeObject 反序列化物件
            string strresult = "";
            foreach (Departments line in Enmity)
            {
                strresult += line.OrgCode + "  " + line.DeptCode + "  " + line.DeptName + "\r\n";
            }
            TexResult.Text = strresult;
        }

相關文章