在嵌套对象上使用 JsonConvert.DeserializeObject [英] Using JsonConvert.DeserializeObject on Nested Object
问题描述
我想在我的应用程序加载时使用 JSON.Net 来处理配置文件的解析.将所有 KVP 保持在同一范围内绝对没问题.但是,我想将其分解为子类别,例如 Settings.WebServer、Settings.GameServer 等.
I want to use JSON.Net to handle parsing a configuration file when my application is loaded. Keeping all KVP's in the same scope works absolutely fine. I would however like to break it down into sub-categories such as Settings.WebServer, Settings.GameServer, etc.
为了便于阅读,我希望能够以这种方式引用各种设置,例如 Settings.WebServer.hostname.目前试图将 WebServer/GameServer 考虑在内的因素正在抛弃这一点.任何人都可以帮助我们做些什么来使其正常工作?
I would like to be able to reference various settings in that manner for readability sake, such as Settings.WebServer.hostname. Currently trying to factor in WebServer/GameServer is throwing this off. Can anyone help with what can be done to get this working?
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# 设置类
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; }
}
}
}
推荐答案
您正在尝试序列化/反序列化没有任何属性的 Settings 类,对于您创建的结构,您必须序列化/反序列化 RootObject 类.
You are trying to serialize/deserialize the Settings class which does not have any property, for the structure you created you must serialize/deserialize the class RootObject.
>
如果您想使用 Settings 类,请将其更改为:
If you want to use the Settings class change it to this:
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; }
}
}
这篇关于在嵌套对象上使用 JsonConvert.DeserializeObject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!