将字典<string, string>转换为对象

问题描述 投票:0回答:1

我有字典是班级的投影。 例如:

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; }

字典值可能是:

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

我想将此字典反序列化为单个对象

AppSettings

我知道 ASP.Net 6.0 中有内置的这种类型的反序列化器,但我在它所指的

ComponentModel.TypeConverter
中找不到它。

app.Configuration.Bind(new object());
c# asp.net converters
1个回答
0
投票

使用以下方法:

static T ConvertDictionaryToObject(Dictionarydictionary) 其中 T : new() { T obj = new T();

        foreach (var kvp in dictionary)
        {
            PropertyInfo property = typeof(T).GetProperty(kvp.Key);

            if (property != null)
            {
                // Convert the string value to the property type
                object value = Convert.ChangeType(kvp.Value, property.PropertyType);

                // Set the property value
                property.SetValue(obj, value);
            }
        }

        return obj;
    }

像这样使用它:

var appSetting = ConvertDictionaryToObject<AppSettings>(dictionary);
© www.soinside.com 2019 - 2024. All rights reserved.