[英]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:但是,当我尝试使用
dynamic
对象时,出现异常:
System.Reflection.TargetParameterCountException: Parameter count mismatch.
System.Reflection.TargetParameterCountException:参数计数不匹配。
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.我在这里尝试了一些解决方案(例如
object foo = dynamic obj
然后使用obj
)但似乎没有一个工作,因为它们并没有完全反映我的问题。
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:如果您真的想要反序列化 JSON 的属性,您可以按照 docs 的说明进行操作,尽管您可能会对输出感到惊讶:
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).但是如果你只想从 JSON 本身获取属性,这有点棘手(虽然不确定这段代码是否最优)。 Note, this code doesn't cover case of nested JSON objects:
请注意,此代码不涵盖嵌套 JSON 对象的情况:
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;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.