Advertisement
DigitalMag

Serialize/deserialize string

Jun 3rd, 2020
1,277
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.60 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.IO;
  6.  
  7. namespace Model
  8. {
  9.     public class Message
  10.     {
  11.         public string Name { get; set; }
  12.         public int Age { get; set; }
  13.     }
  14. }
  15.  
  16. namespace Xamarin
  17. {
  18.     class Program
  19.     {
  20.  
  21.         private static string Serialize(List<Model.Message> messages)
  22.         {
  23.             System.Xml.Serialization.XmlSerializer xml = new System.Xml.Serialization.XmlSerializer(messages.GetType());        
  24.  
  25.             using (StringWriter textWriter = new StringWriter())
  26.             {
  27.                 xml.Serialize(textWriter, messages);
  28.                 var objs = textWriter.ToString();
  29.                 return objs;
  30.             }
  31.         }
  32.  
  33.         public static List<Model.Message> Deserialize(string messages)
  34.         {
  35.  
  36.             System.Xml.Serialization.XmlSerializer xml = new System.Xml.Serialization.XmlSerializer(typeof(List<Model.Message>));
  37.  
  38.             using (StringReader sr = new StringReader(messages))
  39.             {
  40.                 var r = xml.Deserialize(sr) as List<Model.Message>;
  41.                 return r;
  42.             }
  43.         }
  44.  
  45.         static void Main(string[] args)
  46.         {
  47.             var messages = new List<Model.Message>()
  48.             {
  49.                 new Model.Message{Name = "Hohn", Age = 19},
  50.                 new Model.Message{Name = "Anna", Age = 17}
  51.             };
  52.  
  53.             var str = Serialize(messages);
  54.  
  55.             var lst = Deserialize(str);
  56.  
  57.             Console.WriteLine(lst.First().Name);
  58.             Console.Read();
  59.         }
  60.     }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement