Add JSON storage engine
This commit is contained in:
parent
c5721159a4
commit
e777427de8
3 changed files with 43 additions and 2 deletions
10
Product.cs
10
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<Product> (json);
|
||||
}
|
||||
|
||||
public void display() {
|
||||
string output = String.Format(@"
|
||||
{0}
|
||||
|
|
21
Storage.cs
21
Storage.cs
|
@ -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
14
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
Reference in a new issue