-
Notifications
You must be signed in to change notification settings - Fork 0
/
JsonSerializer.cs
64 lines (47 loc) · 1.48 KB
/
JsonSerializer.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
53
54
55
56
57
58
59
60
61
62
63
64
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.IO;
namespace Zenvin.Settings.Framework.Serialization {
public class JsonSerializer : ISerializer<JObject> {
private JObject data;
public JsonSerializer () {
data = new JObject ();
}
public bool ReadFromFile (FileInfo file) {
if (file == null || !file.Exists) {
return false;
}
// prepare json reader
using FileStream stream = file.OpenRead ();
using StreamReader reader = new StreamReader (stream);
using JsonTextReader jsonReader = new JsonTextReader (reader);
// read json data
JObject jData = JToken.ReadFrom (jsonReader) as JObject;
data = jData;
// return whether reading data was successful
return data != null;
}
public bool WriteToFile (FileInfo file, Formatting formatting = Formatting.Indented, params JsonConverter[] converters) {
if (file == null) {
return false;
}
string json = JsonConvert.SerializeObject (data, formatting, converters);
File.WriteAllText (file.FullName, json);
return true;
}
IEnumerator<KeyValuePair<string, JObject>> ISerializer<JObject>.GetSerializedData () {
foreach (var item in data) {
if (item.Value is JObject jObject) {
yield return new KeyValuePair<string, JObject> (item.Key, jObject);
}
}
}
void ISerializer<JObject>.Serialize (string guid, JObject value) {
data[guid] = value;
}
public override string ToString () {
return data.ToString ();
}
}
}