JSON/XML序列化與還原序列化(非構造自訂類)

來源:互聯網
上載者:User

標籤:des   style   blog   http   color   io   os   ar   使用   

隔了很長時間再重看自己的代碼,覺得好陌生。。以後要養成多注釋的好習慣。。直接貼代碼。。對不起( ▼-▼ )

儲存儲存:進行序列化後存入應用設定裡

ApplicationDataContainer _appSettings = ApplicationData.Current.LocalSettings;  //這個是儲存一些頁面輸入資訊private async void Save_Click(object sender, RoutedEventArgs e) { if (userName.Text == "" || userAge.Text == "") { await new MessageDialog("請輸入完整的資訊").ShowAsync(); return; } ObservableCollection<School> education = new ObservableCollection<School>(); if (school1.IsChecked == true) education.Add(new School() { Id = "id001", Name = school1.Content.ToString() }); if (school2.IsChecked == true) { education.Add(new School() { Id = "id002", Name = school2.Content.ToString() }); } User user = new User() { Education = education, Id = Guid.NewGuid().ToString(),//隨機產生 前面用到過的 Name = userName.Text, Age = Int32.Parse(userAge.Text), Verified = false }; //使用DataContractJsonDeSeriaLizer實現方式 string json = ToJsonData(user); //帶參數的建構函式 //string json = user.Stringify();//這個是構造自訂的類的,此處用不到 info.Text = json; _appSettings.Values["UserDataKey"] = json; //存放到應用設定裡面 await new MessageDialog("儲存成功").ShowAsync(); }

擷取資料:從應用設定取出,進行還原序列化取出資訊

private async void Get_Click(object sender, RoutedEventArgs e)        {            if (!_appSettings.Values.ContainsKey("UserDataKey")) { await new MessageDialog("未儲存資訊").ShowAsync(); return; } string json = _appSettings.Values[UserDataKey].ToString(); //還原序列化為實體類對象 User user = DataContractJsonSerializer<User>(json); //User user = new User(json); string userInfo = ""; userInfo = "Id:" + user.Id + "Name:" + user.Name + "Age:" + user.Age; foreach (School school in user.Education) { userInfo += "Education:" + "Id:" + school.Id + "name:" + school.Name; } await new MessageDialog(userInfo).ShowAsync(); }private T DataContractJsonSerializer<T>(string jsonString) { var ds = new DataContractJsonSerializer(typeof(T)); var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)); T obj = (T)ds.ReadObject(ms); ms.Dispose(); return obj; }

不貼了。。看的好難受。。以後再也不會這麼敷衍了。大家多看看其他的也行。

 

收穫:

ObservableCollection<>相對List<>來說,綁定到ListBox會自動重新整理

也就是當你在進行增加、刪除操作時,前台會動態顯示。

 

有需要源碼(WP8.1)的可以下載。包含了JSON/Xml的兩種(構造與不構造類)操作方式。。

http://files.cnblogs.com/yffswyf/JSONAndXML.rar

JSON/XML序列化與還原序列化(非構造自訂類)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.