From e777427de8643983b6a4b41832875b333e7d653b Mon Sep 17 00:00:00 2001 From: Jake Howard Date: Fri, 15 Apr 2016 14:58:45 +0100 Subject: [PATCH] Add JSON storage engine --- Product.cs | 10 +++++++++- Storage.cs | 21 +++++++++++++++++++++ UI.cs | 14 +++++++++++++- 3 files changed, 43 insertions(+), 2 deletions(-) diff --git a/Product.cs b/Product.cs index 1743303..686be34 100644 --- a/Product.cs +++ b/Product.cs @@ -1,5 +1,5 @@ using System; - +using Newtonsoft.Json; namespace productlist { @@ -27,6 +27,14 @@ namespace productlist return String.Format ("Product {0}", this.name); } + public string serialize() { + return JsonConvert.SerializeObject (this); + } + + public static Product fromJSON(string json) { + return JsonConvert.DeserializeObject (json); + } + public void display() { string output = String.Format(@" {0} diff --git a/Storage.cs b/Storage.cs index 078b4fa..97be652 100644 --- a/Storage.cs +++ b/Storage.cs @@ -1,16 +1,37 @@ using System; using System.Collections.Generic; +using Newtonsoft.Json; namespace productlist { public static class Storage { private static List productStorageList = new List(); + private static readonly string filePath = @"data.json"; public static void Add(Product p) { productStorageList.Add (p); } + public static void dump() { + if (productStorageList.Count < 1) { + Console.WriteLine ("Nothing to dump"); + return; + } + string json = JsonConvert.SerializeObject (productStorageList); + System.IO.File.WriteAllText (filePath, json); + + } + + public static void load() { + if (!System.IO.File.Exists (filePath)) { + Console.WriteLine ("Data file not found!"); + return; + } + string text = System.IO.File.ReadAllText (filePath); + productStorageList = JsonConvert.DeserializeObject> (text); + } + private static void listProducts() { if (productStorageList.Count < 1) { Console.WriteLine ("No Products found!"); diff --git a/UI.cs b/UI.cs index 7abd907..c1cd5a2 100644 --- a/UI.cs +++ b/UI.cs @@ -8,7 +8,9 @@ namespace productlist create, delete, list, - help + help, + dump, + load } private static inputType decodeInputType(string input) { string command = input.Split (null, 1)[0]; @@ -22,6 +24,10 @@ namespace productlist default: case "help": return inputType.help; + case "dump": + return inputType.dump; + case "load": + return inputType.load; } } @@ -56,6 +62,12 @@ namespace productlist case inputType.list: Storage.List (); break; + case inputType.dump: + Storage.dump (); + break; + case inputType.load: + Storage.load (); + break; } } }