如何配置 JSON Configuration Section?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (50)

是否有一种方法可以用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"
        }
    ]
}
提问于
用户回答回答于

只需将JSON映射到XML中即可。然后,您可以通过编辑.proj XML文件将Gulp任务添加到您的构建步骤中(GULP应该在正在执行构建的机器上全局安装)。

  1. 在文本编辑器中打开proj文件,并找到以下部分:<Project> <Target Name="BeforeBuild"> <!-- Insert tasks to run before build here --> </Target> </Project>
  2. 用GUMP命令。
用户回答回答于

库: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.

扫码关注云+社区

领取腾讯云代金券