vendredi 23 juin 2023

Get nested property name and its value from object C#

I have an object and I want to get full primitive property path and its value.

Type1 Prop1
   |_ Type2 Prop 2
         |_ string Text
   |_ Type3 Prop3
         |_ Type4 Prop4
                |_ int Number
    ...

What I tried so far:

var props = obj.Prop1.GetType().GetProperties();

foreach (var prop in props)
{
     var name = GetData(prop, obj);
     // add name to list
}
static bool IsPrimitive(Type t)
{
    return t.IsPrimitive || t == typeof(string);
}
static KeyValuePair<string,object> GetData(PropertyInfo property, object reference)
{
            if (IsPrimitive(property.PropertyType))
            {
                return new KeyValuePair<string, object>(property.Name, property.GetValue(reference,null));
            }

            var props = property.PropertyType.GetProperties();
            var name = property.Name;
            object value = null;

            foreach (var p in props)
            {
                name += $".{GetData(p, reference)}.";
                value = p.GetValue(reference, null);

                if (IsPrimitive(p.PropertyType))
                {
                    break;
                }
            }

            return new KeyValuePair<string, object>(name.Trim('.'), value);
}

The problem is that for GetValue(reference, null), I get exception:

'Object does not match target type.'

What I'm doing wrong ? I tried:

GetData(prop, obj); also GetData(prop, obj.Prop1);, but same error

The expected output would be:

Prop1.Prop2.Text and its value
Prop1.Prop3.Prop4.Number and its value




Aucun commentaire:

Enregistrer un commentaire