Как преобразовать словарь в класс и подклассы рекурсивно? Это мои классы:Конвертировать словарь <string, object> в класс и подкласс
public class UiItem
{
public string id { get; set; }
public string text { get; set; }
public Rect rect { get; set; }
}
public class Rect
{
public int height { get; set; }
public int width { get; set; }
public int y { get; set; }
public int x { get; set; }
}
Я написал это, но я не знаю, как создать объект Rect
в классе UiItem
:
public static T GetObject<T>(this Dictionary<string, object> dict)
{
Type type = typeof(T);
var obj = Activator.CreateInstance(type);
foreach (var kv in dict)
{
var prop = type.GetProperty(kv.Key);
object value = kv.Value;
if (kv.Value.GetType() == typeof(Dictionary<string, object>))
{
value = GetObject<_???_>((Dictionary<string, object>) value) // <= This line
}
if(prop == null) continue;
prop.SetValue(obj, value, null);
}
return (T)obj;
}
ли Ваша структура объекта 'n' уровней вложенности? Если это всего лишь 2 уровня, то почему бы не взять 2 типа параметров? – user1620220