构建JSON配置部分 [英] Building a JSON Configuration Section

查看:160
本文介绍了构建JSON配置部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法用JSON而不是XML编写配置节?

Is there a way to have configuration sections written in JSON instead of 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配置部分:

I can then create the following XML configuration section:

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

我想要实现的是mantain 相同的UsersConfig类但是我不想映射到XML,我想将它映射到一个JSON:

What I would want to achieve is to mantain the same UsersConfig class, but instead of mapping it to XML, I would like to map it to a JSON:

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


推荐答案

https://github.com/Dynalon/JsonConfig

从文档:


JsonConfig是一个简单易用的配置库,允许JSON
基于配置文件C#/。NET应用程序而不是繁琐的
web.config / application.config xml文件。它基于JsonFX和C#
4.0动态特性。允许将您的程序配置文件放入.json文件,其中默认配置可以作为资源嵌入或
放在(web-)应用程序文件夹中。配置可以通过
动态类型访问,不需要自定义类或任何其他存根代码。
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.

这篇关于构建JSON配置部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆