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 System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Metadata;
using System.Text.Json.Nodes;
using Newtonsoft.Json.Linq;
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 JsonExtensions
{
public static Action<JsonTypeInfo> InitializePropertyNamesFromConfiguration(IConfiguration config) =>
typeInfo =>
{
if (typeInfo.Kind == JsonTypeInfoKind.Object)
foreach (var property in typeInfo.Properties)
if ((property.AttributeProvider?
.GetCustomAttributes(typeof(JsonConfiguredPropertyNameAttribute), true)
.Cast<JsonConfiguredPropertyNameAttribute>()
.SingleOrDefault()?.Key) is {} key)
property.Name = config[key] ?? property.Name;
};
}
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 options = new JsonSerializerOptions();
options.TypeInfoResolver = new DefaultJsonTypeInfoResolver
{
Modifiers = { JsonExtensions.InitializePropertyNamesFromConfiguration(config) },
};
// Add other options as required, e.g.
options.PropertyNamingPolicy = JsonNamingPolicy.CamelCase;
options.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
options.WriteIndented = true;
var project = JsonSerializer.Deserialize<Project>(inputJson, options);
var outputJson = JsonSerializer.Serialize(project, options);
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");
}
}
}