PowerToys/Wox.Infrastructure/Storage/JsonStorage.cs

52 lines
1.4 KiB
C#
Raw Normal View History

using System;
using System.IO;
2015-01-23 21:52:46 +08:00
using System.Threading;
using Newtonsoft.Json;
namespace Wox.Infrastructure.Storage
{
/// <summary>
/// Serialize object using json format.
/// </summary>
public abstract class JsonStrorage<T> : BaseStorage<T> where T : class, IStorage, new()
{
2015-01-23 21:52:46 +08:00
private static object syncObject = new object();
protected override string FileSuffix
{
get { return ".json"; }
}
protected override void LoadInternal()
{
string json = File.ReadAllText(ConfigPath);
if (!string.IsNullOrEmpty(json))
{
try
{
serializedObject = JsonConvert.DeserializeObject<T>(json);
}
catch (Exception)
{
serializedObject = LoadDefault();
}
}
else
{
serializedObject = LoadDefault();
}
}
protected override void SaveInternal()
{
2015-01-23 21:52:46 +08:00
ThreadPool.QueueUserWorkItem(o =>
{
lock (syncObject)
{
string json = JsonConvert.SerializeObject(serializedObject, Formatting.Indented);
File.WriteAllText(ConfigPath, json);
}
});
}
}
}