Home > other >  Getting property values inside object using reflection doesn't work
Getting property values inside object using reflection doesn't work

Time:07-07

Trying to get into reflection and as a noob I don't understand why this isn't working.

foreach (var p in localStorageProfile.GetType().GetProperties())
{
    userprofile.Name = p.GetValue("name").ToString();
    userprofile.PhotoUrl = p.GetValue("photoUrl").ToString();
}

I used ToString because they should be strings

This is the exception

System.Reflection.TargetException: Object does not match target type. at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)

And the object as it comes from the client looks like this:

{{"id":0,"name":"Mollie","photoUrl":"assets/images/portraits/1.png","imagePublicId":null... I wanna get properties inside the object type this way because I wanna get into reflection a little bit to get used to it. And this code should work

CodePudding user response:

I would assume that in the example you have provided the variable localStorageProfile is of type string and contains the JSON data.

This would mean that localStorageProfile.GetType().GetProperties() is equivalent to writing out typeof(System.String).GetProperties() which would ultimately return properties of the System.String class and not JSON values.

Usually you want to use the reflection methods GetProperty() and GetProperties() with class objects that actually contain useful property information.

An primitive example could be:

public class Profile
{
    public Profile() { }

    public Profile(int id, string name, string photoUrl)
    {
        this.Id = id;
        this.Name = name;
        this.PhotoUrl = photoUrl;
    }

    public int Id { get; set; }
    public string Name { get; set; }
    public string PhotoUrl { get; set; }
}

// Creating a sample profile
var dollie = new Profile(1, "Dollie", "assets/images/portraits/2.png");

// Creating an empty profile
var copyOfDollie = new Profile();

// Filling the empty profile using reflection
copyOfDollie.Id = (int)typeof(Profile).GetProperty("Id").GetValue(dollie);
copyOfDollie.Name = (string)typeof(Profile).GetProperty("Name").GetValue(dollie);
copyOfDollie.PhotoUrl = (string)typeof(Profile).GetProperty("PhotoUrl").GetValue(dollie);

If you just intended to parse the JSON instead use the JsonSerializer class:

string json = @"{
                   ""Id""  : 0,
                   ""Name"": ""Mollie"",
                   ""PhotoUrl"": ""assets/images/portraits/1.png""
                }";

var mollie = JsonSerializer.Deserialize<Profile>(json);
  •  Tags:  
  • c#
  • Related