0
var appsettings = JsonConvert.DeserializeObject<AppSettings<PersonModel>>(configData);

class AppSettings<T>
{
    [JsonProperty(PropertyName = typeof(T).Name)]
    public T dynproperty { get; set; }
}

Appsettings.json content:

{
  "PersonModel": {
    "name": "tempname",
    "active": true
  },
  "CarType":{
    "segment": "sedan",
    "seating" 5
  }
}

In the above class, T will be any model class.

The name of dynproperty has to be set dynamically so that during deserialization from a JSON, the respective model type will be picked by the deserializer.

PS: I am open to any other method, too.

2
  • You certainly can't do it with attributes, they can only accept constant values. I can't provide a full answer as I'm not extremely familiar with json.net but I think you have to use a JsonConverter. newtonsoft.com/json/help/html/SerializeWithJsonConverters.htm
    – Tarazed
    Commented Jul 3 at 16:55
  • @Tarazed You are right, it only takes constant values. That's why I had hard time finding a solution. Tried several ways, all leading to dead ends.
    – Imran K
    Commented Jul 3 at 17:19

1 Answer 1

1

@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.

1
  • Your solution doesn't seem to rightly recognize the property name. I have tried implementing the solution, it doesn't works. Sharing this fiddler link for your reference : Fiddler Code Refernce
    – Imran K
    Commented Jul 4 at 6:52

Not the answer you're looking for? Browse other questions tagged or ask your own question.