【问题标题】:Newtonsoft.Json Serialize / Deserialize static classNewtonsoft.Json 序列化/反序列化静态类
【发布时间】:2020-06-07 22:09:39
【问题描述】:

我有一个静态类,例如:

public static Config
{
    public static string ServerIP;
    ...
}

我将其设为静态,因为它可以在整个应用程序中轻松访问。

现在的问题是,如何序列化/反序列化它?因为这些配置会改变,使用可能会修改json文件中的值。

【问题讨论】:

  • 这能回答你的问题吗? Serialize a Static Class?
  • @HeyJude,是和否。是的,因为它提到静态类不可序列化。否,因为提供的解决方案(使用反射)确实适用于 Xml,但不适用于 Json 序列化程序。
  • @HeyJude。实例化的能力与序列化无关。如果我今天要编写自己的序列化程序,我相信为静态类完成一个序列化程序不会有任何困难。
  • 谷歌序列化

标签: serialization json.net static-classes


【解决方案1】:

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

【讨论】:

  • 经过测试,它可以工作,不是很容易使用,但似乎是目前唯一的解决方案。谢谢
猜你喜欢
  • 2012-10-31
  • 1970-01-01
  • 2022-01-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多