我有字典
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());
使用以下方法:
static T ConvertDictionaryToObject(Dictionary
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);