using System;
using System.IO;
using System.Threading;
using Newtonsoft.Json;
namespace Wox.Infrastructure.Storage
{
///
/// Serialize object using json format.
///
public abstract class JsonStrorage : BaseStorage where T : class, IStorage, new()
{
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(json);
}
catch (Exception)
{
serializedObject = LoadDefault();
}
}
else
{
serializedObject = LoadDefault();
}
}
protected override void SaveInternal()
{
ThreadPool.QueueUserWorkItem(o =>
{
lock (syncObject)
{
string json = JsonConvert.SerializeObject(serializedObject, Formatting.Indented);
File.WriteAllText(ConfigPath, json);
}
});
}
}
}