Advertisement
Zenn_

JSON.NET array serialization

Aug 17th, 2017
209
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.94 KB | None | 0 0
  1. using System;
  2. using Newtonsoft.Json;
  3.  
  4. namespace Json.NET_tests
  5. {
  6. public class Can
  7. {
  8. public enum Brand
  9. {
  10. CocaCola = 0,
  11. Pepsi = 1,
  12. DrPepper = 2
  13. };
  14. public Brand brand;
  15. public float price;
  16. public string flavour;
  17. }
  18.  
  19. class Program
  20. {
  21. static void Main(string[] args) {
  22. Can[] cans = new Can[100];
  23.  
  24. for(int i = 0; i < cans.Length; i++)
  25. {
  26. Random rnd = new Random(i);
  27. Can temp = new Can();
  28. temp.brand = (Can.Brand)rnd.Next(0, 4);
  29. temp.price = ((float)rnd.Next(50, 151)) / 100f;
  30. switch(rnd.Next(0, 4))
  31. {
  32. case 0:
  33. temp.flavour = "Cola";
  34. break;
  35. case 1:
  36. temp.flavour = "Lemon";
  37. break;
  38. case 2:
  39. temp.flavour = "Ass";
  40. break;
  41. case 3:
  42. temp.flavour = "Coffee";
  43. break;
  44. }
  45. cans[i] = temp;
  46. }
  47.  
  48. String ser = JsonConvert.SerializeObject(cans);
  49. Console.Write(ser);
  50. Console.ReadLine();
  51. Can[] cans2 = JsonConvert.DeserializeObject<Can[]>(ser);
  52. for (int i = 0; i < cans.Length; i++)
  53. {
  54. Console.ForegroundColor = ConsoleColor.Cyan;
  55. Console.WriteLine("Can number" + (i+1) + ":");
  56. Console.ForegroundColor = ConsoleColor.White;
  57. Console.WriteLine(cans2[i].brand);
  58. Console.WriteLine(cans2[i].price);
  59. Console.WriteLine(cans2[i].flavour);
  60. Console.WriteLine();
  61. }
  62. Console.ReadLine();
  63. }
  64. }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement