Mat*_*ero 20 c# xml configuration json c#-4.0
有没有办法让配置部分用JSON而不是XML编写?
我们假设我有以下内容ConfigurationSection:
public class UsersConfig : ConfigurationSection {
[ConfigurationProperty("users",
IsRequired = false)]
public UserCollection Users {
get { return this["users"] as UserCollection; }
}
}
[ConfigurationCollection(typeof(UserElement),
AddItemName = "user"]
public class UsersCollection : ConfigurationElementCollection {
protected override ConfigurationElement CreateNewElement() {
return new UserElement();
}
protected override object GetElementKey(ConfigurationElement element) {
return ((UserElement)element).Name;
}
}
public class UserElement : ConfigurationElement {
[ConfigurationProperty("name",
IsRequired = true,
IsKey = true)]
public string Name {
get { return this["name"] as string; }
set { this["name"] = value; }
}
}
Run Code Online (Sandbox Code Playgroud)
然后,我可以创建以下XML配置部分:
<users-config>
<users>
<user name="Matt458" />
<user name="JohnLennon" />
</users>
</users-config>
Run Code Online (Sandbox Code Playgroud)
我想要实现的是保持相同的UsersConfig类,但是我想将它映射到JSON而不是映射到XML:
{
"users": [
{
"name": "Matt458"
},
{
"name": "JohnLennon"
}
]
}
Run Code Online (Sandbox Code Playgroud)
小智 0
您可以更改自己的 UsersConfig 类,使其能够序列化和反序列化为 JSON。然后编写另一个类来从您的文件中检索配置。在 app.config 中,您可以添加单个设置,将您指向存储 json 配置的位置。
您可以通过使用 Json.Net 并向 UsersConfig 类添加属性来轻松实现此目的。
| 归档时间: |
|
| 查看次数: |
22632 次 |
| 最近记录: |