简体   繁体   中英

Get Properties From Dynamic Deserialized Json Object with Reflection - .NET Core 3.1 C#

I am currently learning how to do reflection and I have been succesful with regards to getting the propeties and values of a stringly typed class. However, when I try with a dynamic object, I get an exception:

System.Reflection.TargetParameterCountException: Parameter count mismatch.

I've tried some of the solutions (eg object foo = dynamic obj then using obj ) here but none seem to work because they don't quite reflect my problem.

Here is my code:

dynamic evtPc1 = JsonConvert.DeserializeObject(json);

PropertyInfo[] properties = evtPc1.GetType().GetProperties();

for (int i = 0; i < properties.Length; i++)
{
    Console.WriteLine($"Property: {properties[i].GetValue(evtPc1)}");
}

If you really want properties of deserialized JSON you could do what docs says, though you may be surprised with the output:

dynamic evtPc1 = JsonConvert.DeserializeObject(json);
PropertyInfo[] properties = evtPc1.GetType().GetProperties();
for (int i = 0; i < properties.Length; i++)
{
    var prop = properties[i];

    if (prop.GetIndexParameters().Length == 0)
        Console.WriteLine("{0} ({1}): {2}", prop.Name,
            prop.PropertyType.Name,
            prop.GetValue(evtPc1));
    else
        Console.WriteLine("{0} ({1}): <Indexed>", prop.Name,
            prop.PropertyType.Name);
}

But if you want get only properties from JSON itself, this is a bit more tricky (not sure if this code is optimal though). Note, this code doesn't cover case of nested JSON objects:

dynamic evtPc1 = JsonConvert.DeserializeObject(json);
PropertyInfo[] properties = evtPc1.GetType().GetProperties();
for (int i = 0; i < properties.Length; i++)
{
    var prop = properties[i];

    if (prop.Name == nameof(JToken.First) && prop.PropertyType.Name == nameof(JToken))
    {
        var token = (JToken) prop.GetValue(evtPc1);
        while (token != null)
        {
            if (token is JProperty castProp)
                Console.WriteLine($"Property: {castProp.Name}; Value: {castProp.Value}");

            token = token.Next;
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM