Search code examples
c#asp.netconverters

Converting Dictionary<string, string> to object


I have Dictionary<string, string> is projection of class. For example:

public class AppSettings {
    public int? S { get; }
    public double? SS { get; }
    public string? SSS { get; }
    public bool? SSSS { get; }

    public G? G { get; }
}
public class G {
    public int[] GG { get; }

The dictionary values may be:

"S", "5"
"SS", "5.2"
"SSS", "string",
"SSSS", "true"
"G:GG", "[1, 2, 3]"

I want to deserialize this dictionary to the single object AppSettings.

I know there is built-in this type of deserializator in ASP.Net 6.0, but I can't find it in ComponentModel.TypeConverter which it refers to.

app.Configuration.Bind(new object());

Solution

  • Use the below method :

    static T ConvertDictionaryToObject<T>(Dictionary<string, string> dictionary) where T : new()
            {
                T obj = new T();
        
                foreach (var kvp in dictionary)
                {
                    PropertyInfo property = typeof(T).GetProperty(kvp.Key);
        
                    if (property != null)
                    {
                        
                        object value = Convert.ChangeType(kvp.Value, property.PropertyType);
        
                        
                        property.SetValue(obj, value);
                    }
                }
        
                return obj;
            }
    

    Use it like :

    var appSetting = ConvertDictionaryToObject<AppSettings>(dictionary);