JsonSettings
This library simplifies creating configuration for your C# app/service by utilizing the serialization capabilities of Json.NET to serialize nested (custom) objects, dictionaries and lists as simply as by creating a POCO and inheriting JsonSettings class.
Install / Use
/learn @Nucs/JsonSettingsREADME
<img src="https://i.imgur.com/BOExs52.png" width="25" style="margin: 5px 0px 0px 10px"/> JsonSettings
This library aims to simplify the process of creating configuration for your C# app/service
by utilizing the serialization capabilities of Json.NET
to serialize nested (custom) objects, dictionaries and lists as simply as by creating a POCO and inheriting JsonSettings class.<br/>
Installation
PM> Install-Package nucs.JsonSettings
Table of Contents
- Features Overview
- The Basics
- Modules
- Dynamic Settings Bag
- Changing JsonSerializerSettings
- Converters
- Modulation Api
- License
Features Overview
- Initialized in a fluent static API <span style='font-size:11px; padding-left: 3px' >read more</span>
- Cross-platform targeting
netstandard2.0 - Modularity allowing easy extension and high control over behavior on a per-object level <span style='font-size:11px; padding-left: 3px' >read more</span>
- Autosaving on changes <span style='font-size:11px; padding-left: 3px' >read more</span>
- Via
INotificationChanged/INotificationCollectionChangedallowing WPF binding (with interval throttling support to avoid cpu overload) <span style='font-size:11px; padding-left: 3px' >read more</span> - Via
Castle.DynamicProxygenerated wrapper <span style='font-size:11px; padding-left: 3px' >read more</span>
- Via
- Versioning control <span style='font-size:11px; padding-left: 3px' >read more</span>
- Offers protection mechanisms such as renaming file and loading default
- By changing version, it allows to introduce any kind of changes to the settings class
- Customizable control over recovering from parsing exceptions <span style='font-size:11px; padding-left: 3px' >read more</span>
- AES256 Encryption via a key <span style='font-size:11px; padding-left: 3px' >read more</span>
- Fully extensible with Json.NET 's capabilities, attributes and settings
- It'll be accurate to say that this library is built around Json.NET
SettingsBag, adynamicoption that uses a ConcurrentDictionary<string,object> eliminating the need for hardcoding POCO class <span style='font-size:11px; padding-left: 3px' >read more</span>
The Basics
Test project: https://github.com/Nucs/JsonSettings/tree/master/tests/JsonSettings.Tests <br> Serialization Guide: https://www.newtonsoft.com/json/help/html/SerializationGuide.htm </br>
JsonSettings is the base abstract class serving as the base class for all settings objects the user defines. <br>
Creation, loading is done through static API where saving is through the settings object API.
Here is a self explanatory quicky of to how and what:
- Hardcoded settings
//Step 1: create a class and inherit JsonSettings
class MySettings : JsonSettings {
//Step 2: override a default FileName or keep it empty. Just make sure to specify it when calling Load!
//This is used for default saving and loading so you won't have to specify the filename/path every time.
//Putting just a filename without folder will put it inside the executing file's directory.
public override string FileName { get; set; } = "TheDefaultFilename.extension"; //for loading and saving.
#region Settings
public string SomeProperty { get; set; }
public Dictionary<string, object> Dictionary { get; set; } = new Dictionary<string, object>();
public int SomeNumberWithDefaultValue { get; set; } = 1;
[JsonIgnore] public char ImIgnoredAndIWontBeSavedOrLoaded { get; set; }
#endregion
//Step 3: Override parent's constructors
public MySettings() { }
public MySettings(string fileName) : base(fileName) { }
}
//Step 4: Load
public MySettings Settings = JsonSettings.Load<MySettings>("config.json"); //relative path to executing file.
//or create a new empty
public MySettings Settings = JsonSettings.Construct<MySettings>("config.json");
//Step 5: Introduce changes and save.
Settings.SomeProperty = "ok";
Settings.Save();
- Dynamic settings
- Dynamic settings will automatically create new keys.
- Can accept any Type that Json.NET can serialize
ValueTypes are returned asNullable<Type>, therefore if a key doesn't exist - a null is returned.
//Step 1: Just load it, it'll be created if doesn't exist.
public SettingsBag Settings = JsonSettings.Load<SettingsBag>("config.json");
//Step 2: use!
Settings["key"] = "dat value tho";
Settings["key2"] = 123;
dynamic dyn = Settings.AsDynamic();
if ((int?)dyn.key2==123)
Console.WriteLine("explode");
dyn.Save(); /* or */ Settings.Save();
- Encrypted settings
- Uses AES/Rijndael
- Can be applied to any settings class because it is a module.
MySettings Settings = JsonSettings.Load<MySettings>("config.json", q=>q.WithEncryption("mysecretpassword"));
SettingsBag Settings = JsonSettings.Load<SettingsBag>("config.json", q=>q.WithEncryption("mysecretpassword"));
//or
MySettings Settings = JsonSettings.Configure<MySettings>("config.json")
.WithEncryption("mysecretpassword")
//or: .WithModule<RijndaelModule>("pass");
.LoadNow();
SettingsBag Settings = JsonSettings.Configure<SettingsBag>("config.json")
.WithEncryption("mysecretpassword")
//or: .WithModule<RijndaelModule>("pass");
.LoadNow();
- Hardcoded Settings with Autosave
- Automatic save will occur when changes detected on virtual properties
- All properties have to be virtual
- Requires package
nucs.JsonSettings.Autosavethat usesCastle.Core.
Settings x = JsonSettings.Load<Settings>().EnableAutosave(); //call after loading
//or:
ISettings x = JsonSettings.Load<Settings>().EnableIAutosave<ISettings>(); //Settings implements interface ISettings
x.Property = "value"; //Saved!
- Dynamic Settings with Autosave
- Automatic save will occur when changes detected
- note: SettingsBag has it's own implementation of EnableAutosave().
//Step 1:
SettingsBag Settings = JsonSettings.Load<SettingsBag>("config.json").EnableAutosave(); //call after loading
//Unavailable for hardcoded settings yet! (ty netstandard2.0 for not being awesome on proxies)
//Step 2:
Settings.AsDynamic().key = "wow"; //Saved!
Settings["key"] = "wow two"; //Saved!
Recovery
RecoveryModule provides handling for JsonException when calling JsonSettings.LoadJson during the loading process.
On a scenario of exception/failure, one of the following actions can take place:
- RecoveryAction.Throw<br/> Will throw JsonSettingsRecoveryException with the real exception as inner exception.
- RecoveryAction.LoadDefault<br/> Default settings will be loaded without touching the existing file until next save.
- RecoveryAction.LoadDefaultAndSave<br/> Default settings will be loaded and saved to disk immediately.
- RecoveryAction.RenameAndLoadDefault<br/>
Will append the version to the end of the faulty file's name and load the default settings and save to disk.<br/>
i.e.
myfile.jsonversioned1.0.0.5will be renamed tomyfile.1.0.0.5.jsonif it fails on parsing and the new default settings will be saved as the original filename.
All recovery properties and methods are suited for inheritance so extending is quite easy.
//TODO: add example
Versioning
VersioningModule<T> provides the ability to enforce a specific version so when new changes are introduced to your Settings class (scheme),
a user-defined action can take place. Any of the following actions can be taken:
- VersioningResultAction.DoNothing<br/> Will keep the old version if it was parsed by Json.NET successfully. otherwise RecoveryModule will handle the failure of loading.
- VersioningResultAction.Throw<br/> Will throw JsonSettingsRecoveryException with the real exception as inner exception.
- VersioningResultAction.LoadDefault<br/> Default settings will be loaded without touching the existing file until next save.
- VersioningResultAction.LoadDefaultAndSave<br/> Default settings will be loaded and saved to disk immediately.
- VersioningResultAction.RenameAndLoadDefault<br/>
Will append the version to the end of the faulty file's name and load the default settings and save to disk.<br/>
i.e.
myfile.jsonversioned1.0.0.5will be renamed tomyfile.1.0.0.5.jsonif it fails on parsing and the new default settings will be saved as the original filename.
There are two ways to specify which version to enforce.
- Pass the version when calling
WithVersioning. - Add
[EnforcedVersion("1.0.0.0")]attribute to your `I
Related Skills
node-connect
343.1kDiagnose OpenClaw node connection and pairing failures for Android, iOS, and macOS companion apps
frontend-design
90.0kCreate distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.
openai-whisper-api
343.1kTranscribe audio via OpenAI Audio Transcriptions API (Whisper).
qqbot-media
343.1kQQBot 富媒体收发能力。使用 <qqmedia> 标签,系统根据文件扩展名自动识别类型(图片/语音/视频/文件)。
