Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading