gpt4 book ai didi

c# - 构建 JSON 配置部分

转载 作者:IT王子 更新时间:2023-10-29 04:44:54 28 4
gpt4 key购买 nike

有没有办法用 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; }
}
}

然后我可以创建以下 XML 配置部分:

<users-config>
<users>
<user name="Matt458" />
<user name="JohnLennon" />
</users>
</users-config>

我想要实现的是维护相同的 UsersConfig 类,但我不想将其映射到 XML,而是将其映射到 JSON:

{
"users": [
{
"name": "Matt458"
},
{
"name": "JohnLennon"
}
]
}

最佳答案

这个图书馆可能会帮助你:https://github.com/Dynalon/JsonConfig :

来自文档:

JsonConfig is a simple to use configuration library, allowing JSON based config files for your C#/.NET application instead of cumbersome web.config/application.config xml files. It is based on JsonFX and C# 4.0 dynamic feature. Allows putting your programs config file into .json files, where a default config can be embedded as a resource or put in the (web-)application folder. Configuration can be accessed via dynamic types, no custom classes or any other stub code is necessary. JsonConfig brings support for config inheritance, meaning a set of configuration files can be used to have a single, scoped configuration at runtime which is a merged version of all provided configuration files.

关于c# - 构建 JSON 配置部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30042795/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com