在嵌套对象上使用JsonConvert.DeserializeObject

时间:2016-02-04 16:13:40

标签: c# json parsing nested application-settings

我希望在加载应用程序时使用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#Main

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

C#设置类

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; }
        }
    }
}

1 个答案:

答案 0 :(得分:3)

您正在尝试序列化/反序列化没有任何属性的Settings类,对于您创建的结构,您必须序列化/反序列化类RootObject。

如果要使用“设置”类,请将其更改为:

    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; }

        }
    }