我有一个静态类,例如:
public static Config
{
public static string ServerIP;
...
}
我将此设为静态,因为可以在整个应用程序中轻松访问它。
现在的问题是,如何对它进行序列化/反序列化?因为这些配置将会更改,使用可能会修改json文件中的值。
答案 0 :(得分:0)
System.Text.Json和Newtonsoft.Json都不支持静态类的序列化。因此,虽然不能直接序列化该类,但是可以序列化其成员。
如果您可以使用Newtonsoft.Json,则可以填充至少类似这样的内容以进行反序列化,并填充类似的内容以进行序列化:
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
static class Config
{
public static string ServerIP = string.Empty;
}
static void DeserializeStaticClass(string json, Type staticClassType)
{
if (!staticClassType.IsClass)
throw new ArgumentException("Type must be a class", nameof(staticClassType));
if (!staticClassType.IsAbstract || !staticClassType.IsSealed)
throw new ArgumentException("Type must be static", nameof(staticClassType));
var document = JObject.Parse(json);
var classFields = staticClassType.GetFields(BindingFlags.Public | BindingFlags.Static);
foreach (var field in classFields)
{
var documentField = document[field.Name];
if (documentField == null)
throw new JsonSerializationException($"Not found in JSON: {field.Name}");
field.SetValue(null, documentField.ToObject(field.FieldType));
}
}
...
DeserializeStaticClass("{\"ServerIP\": \"localhost\"}", typeof(Config));
如果您需要自定义嵌套成员的序列化,则可以将JsonSerializer
传递给documentField.ToObject
。