Advertisement
Guest User

Untitled

a guest
May 29th, 2016
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.38 KB | None | 0 0
  1. name,value
  2. name,value
  3. etc.
  4.  
  5. a,5
  6.  
  7. Car.a = 5;
  8.  
  9. private void AssignProperty(object obj, string propertyName, string propertyValue)
  10. {
  11. PropertyInfo property = obj.GetType().GetProperty(propertyName);
  12. property.SetValue(obj, Convert.ChangeType(propertyValue, property.PropertyType), null);
  13. }
  14.  
  15. public class StringLinesDeserializer<T> where T : new()
  16. {
  17. public T Deserialize(string[] assignments)
  18. {
  19. T result = new T();
  20.  
  21. foreach (string assignment in assignments)
  22. {
  23. int commaPos = assignment.IndexOf(',');
  24. string propertyName = assignment.Substring(0, commaPos);
  25. string propertyValue = assignment.Substring(commaPos + 1);
  26.  
  27. AssignProperty(result, propertyName, propertyValue);
  28. }
  29.  
  30. return result;
  31. }
  32.  
  33. private void AssignProperty(object obj, string propertyName, string propertyValue)
  34. {
  35. PropertyInfo property = obj.GetType().GetProperty(propertyName);
  36. property.SetValue(obj, Convert.ChangeType(propertyValue, property.PropertyType), null);
  37. }
  38. }
  39.  
  40. string[] assignments = new string[]{"a,5","b,6"};
  41. StringLinesDeserializer<Car> deserializer = new StringLinesDeserializer<Car>();
  42. Car newCar = deserializer.Deserialize(assignments);
  43.  
  44. Car car = new Car { a = 10, name = "Golf" };
  45. var str = JsonConvert.SerializeObject(car);
  46.  
  47. {"a":10,"name":"Golf"}
  48.  
  49. Car deserializedCar = JsonConvert.DeserializeObject<Car>(str);
  50.  
  51. var car = new Car { name = "Hellcat", a = 10 };
  52. var serializer = new System.Xml.Serialization.XmlSerializer(typeof(Car));
  53. string carXml = null;
  54. using (var ms = new System.IO.MemoryStream())
  55. {
  56. serializer.Serialize(ms, car);
  57. carXml = System.Text.Encoding.UTF8.GetString(ms.ToArray());
  58. }
  59.  
  60. <?xml version="1.0"?>
  61. <Car xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  62. <a>10</a>
  63. <name>Hellcat</name>
  64. </Car>
  65.  
  66. public class Car
  67. {
  68. public object a { get; set; }
  69. public object b { get; set; }
  70. }
  71.  
  72. private Car GetCarFromFile(string strFilePath)
  73. {
  74. var lstCarFile = System.IO.File.ReadAllLines(strFilePath);
  75.  
  76. var car = new Car();
  77. foreach (var c in lstCarFile)
  78. {
  79. var name = c.Split(',')[0].Trim();
  80. var value = c.Split(',')[1].Trim();
  81.  
  82. car.GetType().GetProperty(name).SetValue(car, value, null);
  83. }
  84.  
  85. return car;
  86. }
  87.  
  88. var car = GetCarFromFile("D:/CarMembersValue.txt");
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement