@Tarazed is right. You should use a JsonConverter. Something like this should work:
class DynamicPropertyNameConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return true;
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var jObject = JObject.Load(reader);
var genericType = objectType.GenericTypeArguments[0];
var genericTypeName = genericType.Name;
var token = jObject[genericTypeName];
if (token == null)
{
throw new JsonSerializationException($"Property '{genericTypeName}' not found.");
}
return token.ToObject(genericType, serializer);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
Your AppSettings class should then have the property and attribute changed, like so:
class AppSettings<T>
{
[JsonConverter(typeof(DynamicPropertyNameConverter))]
public T dynproperty { get; set; }
}
You can then retrieve the settings:
var personSettings = JsonConvert.DeserializeObject<AppSettings<PersonModel>>(configData);
var carSettings = JsonConvert.DeserializeObject<AppSettings<CarModel>>(configData);
So you have to create PersonModel
and CarModel
, which you should have btw.
To access the data in personSettings
, you then use, say, personSettings.dynproperty.name
.