-
Notifications
You must be signed in to change notification settings - Fork 0
/
Json.cs
52 lines (46 loc) · 1.5 KB
/
Json.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.IO;
using System.Collections.Generic;
namespace Snowball
{
public static class Json
{
static JsonSerializerSettings settings = new JsonSerializerSettings()
{
TypeNameHandling = TypeNameHandling.Auto,
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
PreserveReferencesHandling = PreserveReferencesHandling.Objects,
Formatting = Formatting.Indented
};
public static void InitSettings()
{
settings.Converters.Add(new StringEnumConverter());
}
public static void Save(string filename, object obj)
{
var text = JsonConvert.SerializeObject(obj, settings);
File.WriteAllText(filename, text);
}
public static List<T> LoadDirectory<T>(string directory)
{
var files = Directory.GetFiles(directory, "*.json", SearchOption.AllDirectories);
List<T> output = new List<T>();
foreach(var file in files)
{
output.Add(Load<T>(file));
}
return output;
}
public static T Load<T>(string filename)
{
if(!File.Exists(filename))
{
Save(filename, Activator.CreateInstance<T>());
}
var text = File.ReadAllText(filename);
return JsonConvert.DeserializeObject<T>(text, settings);
}
}
}