以下是使用DataContractJsonSerializer
我的實現。它可以在windows和ubuntu 9.04上使用單聲道2.8(使用單聲道2.8來源)。 (當然,它工作在.NET!)我已經從Best Practices: Data Contract Versioning 實施了一些建議。該文件存儲在相同的文件夾作爲EXE(不知道我是否以最好的方式做到了這一點,但它在win和linux中工作)。
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using NLog;
[DataContract]
public class UserSettings : IExtensibleDataObject
{
ExtensionDataObject IExtensibleDataObject.ExtensionData { get; set; }
[DataMember]
public int TestIntProp { get; set; }
private string _testStringField;
}
public static class SettingsManager
{
private static Logger _logger = LogManager.GetLogger("SettingsManager");
private static UserSettings _settings;
private static readonly string _path =
Path.Combine(
Path.GetDirectoryName(
System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName),
"settings.json");
public static UserSettings Settings
{
get
{
return _settings;
}
}
public static void Load()
{
if (string.IsNullOrEmpty(_path))
{
_logger.Trace("empty or null path");
_settings = new UserSettings();
}
else
{
try
{
using (var stream = File.OpenRead(_path))
{
_logger.Trace("opened file");
_settings = SerializationExtensions.LoadJson<UserSettings>(stream);
_logger.Trace("deserialized file ok");
}
}
catch (Exception e)
{
_logger.TraceException("exception", e);
if (e is InvalidCastException
|| e is FileNotFoundException
|| e is SerializationException
)
{
_settings = new UserSettings();
}
else
{
throw;
}
}
}
}
public static void Save()
{
if (File.Exists(_path))
{
string destFileName = _path + ".bak";
if (File.Exists(destFileName))
{
File.Delete(destFileName);
}
File.Move(_path, destFileName);
}
using (var stream = File.Open(_path, FileMode.Create))
{
Settings.WriteJson(stream);
}
}
}
public static class SerializationExtensions
{
public static T LoadJson<T>(Stream stream) where T : class
{
var serializer = new DataContractJsonSerializer(typeof(T));
object readObject = serializer.ReadObject(stream);
return (T)readObject;
}
public static void WriteJson<T>(this T value, Stream stream) where T : class
{
var serializer = new DataContractJsonSerializer(typeof(T));
serializer.WriteObject(stream, value);
}
}
來源
2010-10-15 21:30:02
Pat
在我的測試中,mono 2.8確實實現了這個類。 – Pat 2010-10-15 21:14:35
它看起來像DCJS不以用戶可讀的方式格式化JSON,但它的工作原理! – Pat 2010-10-15 21:24:32
嘗試註釋以獲取更好的元素名稱。看我的編輯。 – 2010-10-18 08:38:22