CSharp · Console
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Data;
using System.Reflection;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
using Microsoft.Extensions.Configuration;
using NUnit.Framework; // Throws NUnit.Framework.AssertionException
#nullable enable
//https://stackoverflow.com/questions/76441698/can-i-use-a-appsettings-json-record-for-jsonpropertyname-in-a-class-model
//References:
// https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-7.0
// https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.configuration.iconfiguration.item?view=dotnet-plat-ext-7.0#microsoft-extensions-configuration-iconfiguration-item(system-string)
// https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.configuration.iconfiguration?view=dotnet-plat-ext-7.0
// https://learn.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-7.0#configuration-keys-and-values
// Hierarchical keys
// Within the Configuration API, a colon separator (:) works on all platforms.
// https://stackoverflow.com/questions/39231951/how-do-i-access-configuration-in-any-class-in-asp-net-core
// https://stackoverflow.com/questions/55790277/dependency-injection-not-working-for-iconfiguration-c-net-core
// https://pradeepl.com/blog/dotnet/configuration-in-a-net-core-console-application/
[System.AttributeUsage(System.AttributeTargets.Property | System.AttributeTargets.Field, AllowMultiple = false, Inherited = true)]
public sealed class JsonConfiguredPropertyNameAttribute : System.Attribute
{
public string Key { get; }
public JsonConfiguredPropertyNameAttribute(string key) => this.Key = key;
}
public class PropertyNamesFromConfigurationContractResolver : DefaultContractResolver
{
readonly IConfiguration config;
public PropertyNamesFromConfigurationContractResolver(IConfiguration config) => this.config = config ?? throw new ArgumentNullException(nameof(config));
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
var property = base.CreateProperty(member, memberSerialization);
if (member.GetCustomAttribute<JsonConfiguredPropertyNameAttribute>()?.Key is {} key)
property.PropertyName = config[key] ?? property.PropertyName;
return property;
}
}
public class Project {
public Project(string projectName) => this.ProjectName = projectName; // Test to make sure this works with both mutable and immutable properties
public string ProjectId { get; set; }
[JsonConfiguredPropertyName("fieldConfig:projectNameField")]
public string ProjectName { get; set; }
[JsonConfiguredPropertyName("fieldConfig:projectDescriptionField")]
public string ProjectDescription { get; set; }
[JsonConfiguredPropertyName("fieldConfig:projectCreatorField")]
public string ProjectCreator { get; set; }
}
class TestClass
{
public static void Test(IConfiguration config)
{
var inputJson = GetRequiredJson();
var settings = new JsonSerializerSettings();
settings.ContractResolver = new PropertyNamesFromConfigurationContractResolver(config)
{
// Add other properties as required, e.g.
NamingStrategy = new CamelCaseNamingStrategy(),
};
// Add other options as required, e.g.
settings.NullValueHandling = NullValueHandling.Ignore;
var project = JsonConvert.DeserializeObject<Project>(inputJson, settings);
var outputJson = JsonConvert.SerializeObject(project, Formatting.Indented, settings);
Console.WriteLine(outputJson);
Assert.That(JToken.DeepEquals(JToken.Parse(inputJson), JToken.Parse(outputJson)));
}
static string GetRequiredJson() =>
"""
{
"fieldA_0001": "name",
"fieldA_0002": "description",
"fieldA_0003": "creator"
}
""";
}
public class Program
{
static string GetJson() =>
"""
{
"fieldConfig": {
"projectNameField": "fieldA_0001",
"projectDescriptionField": "fieldA_0002",
"projectCreatorField": "fieldA_0003"
}
}
""";
public static void Main(string[] args)
{
Console.WriteLine("Environment version: {0} ({1}), {2}", System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription , Environment.Version, Environment.OSVersion);
Console.WriteLine("System.Text.Json version: " + typeof(JsonSerializer).Assembly.FullName);
Console.WriteLine();
File.WriteAllText("appsettings.json", GetJson());
IConfiguration config = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables()
.AddCommandLine(args)
.Build();
try
{
TestClass.Test(config);
}
catch (Exception ex)
{
Console.WriteLine("Failed with unhandled exception: ");
Console.WriteLine(ex);
throw;
}
finally
{
File.Delete("appsettings.json");
}
}
}