在嵌套对象上使用 JsonConvert.DeserializeObject

Using JsonConvert.DeserializeObject on Nested Object

我想在我的应用程序加载时使用 JSON.Net 来处理配置文件的解析。将所有 KVP 保持在同一范围内绝对没问题。但是,我想将其分解为子类别,例如 Settings.WebServer、Settings.GameServer 等

为了便于阅读,我希望能够以这种方式引用各种设置,例如 Settings.WebServer.hostname。目前正在尝试将 WebServer/GameServer 考虑在内,但结果却失败了。任何人都可以帮助完成这项工作吗?

JSON

{
    "webserver":
    {
        "hostname": "localhost",
        "port": "8888"
    },
    "gameserver":
    {
        "hostname": "123.123.123.123",
        "port": "27015",
        "password": "as@c!qi$"
    }
}

C# 主

Settings settings = JsonConvert.DeserializeObject<Settings>(File.ReadAllText(@".\Configs\settings.cfg"));

C# 设置Class

namespace SourceMonitor
{
    public class Settings
    {
        public class Webserver
        {
            [JsonProperty("hostname")]
            public string hostname { get; set; }

            [JsonProperty("port")]
            public string port { get; set; }
        }

        public class Gameserver
        {
            [JsonProperty("hostname")]
            public string hostname { get; set; }

            [JsonProperty("port")]
            public string port { get; set; }

            [JsonProperty("password")]
            public string password { get; set; }
        }

        public class RootObject
        {
            [JsonProperty("webserver")]
            public Webserver webserver { get; set; }

            [JsonProperty("gameserver")]
            public Gameserver gameserver { get; set; }
        }
    }
}

您正在尝试 serialize/deserialize 没有任何 属性 的设置 class,对于您创建的结构,您必须 serialize/deserialize class RootObject.

如果您想使用设置 class 将其更改为:

    namespace SourceMonitor
    {
        public class Settings
        {
            public class Webserver
            {
                [JsonProperty("hostname")]
                public string hostname { get; set; }

                [JsonProperty("port")]
                public string port { get; set; }
            }

            public class Gameserver
            {
                [JsonProperty("hostname")]
                public string hostname { get; set; }

                [JsonProperty("port")]
                public string port { get; set; }

                [JsonProperty("password")]
                public string password { get; set; }
            }

            [JsonProperty("webserver")]
            public Webserver webserver { get; set; }

            [JsonProperty("gameserver")]
            public Gameserver gameserver { get; set; }

        }
    }