Add JSON storage engine

This commit is contained in:
Jake Howard 2016-04-15 14:58:45 +01:00
parent c5721159a4
commit e777427de8
3 changed files with 43 additions and 2 deletions

View file

@ -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<Product> (json);
}
public void display() {
string output = String.Format(@"
{0}

View file

@ -1,16 +1,37 @@
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace productlist
{
public static class Storage
{
private static List<Product> productStorageList = new List<Product>();
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<List<Product>> (text);
}
private static void listProducts() {
if (productStorageList.Count < 1) {
Console.WriteLine ("No Products found!");

14
UI.cs
View file

@ -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;
}
}
}