[英]How to get property value of a dynamic type where property name is in a variable in C#
I am trying to get the value of a property of a dynamic object. 我试图获取动态对象的属性的值。 The json string is parsed/deserialized into a dynamic object and then I want to access the property by name followed by the get value.
json字符串被解析/反序列化为一个动态对象,然后我想按名称访问属性,后跟get值。
string json = "{\"key1\":\"value1\", \"key2\": \"value2\"}";
dynamic d = JObject.Parse(json);
Console.WriteLine("Key1 : " + d.key1); //value1
Above code works as expected but how to get the value using get property by name that is stored in a variable? 上面的代码按预期工作,但是如何通过使用存储在变量中的名称的get属性获取值?
string jsonKey = "key2";
string json = "{\"key1\":\"value1\", \"key2\": \"value2\"}";
dynamic d = JObject.Parse(json);
var jsonValue = d.GetType().GetProperty(jsonKey).GetValue(d, null); //throws exception - Cannot perform runtime binding on a null reference
Console.WriteLine("jsonValue : " + jsonValue);
GetProperty(jsonKey)
throws an exception Cannot perform runtime binding on a null reference
GetProperty(jsonKey)
引发异常Cannot perform runtime binding on a null reference
Or, if there is an alternative solution to this problem. 或者,如果有替代方法可以解决此问题。
Does it have to use Reflection? 是否必须使用反射? You know that JObject.Parse will return JObject, so you can see what are the public methods/ properties.
您知道JObject.Parse将返回JObject,因此您可以看到什么是公共方法/属性。 You can see that it does not expose public property of JSON, hence you cannot get the value.
您会看到它没有公开JSON的公共属性,因此您无法获取该值。
There are several ways to get the value without Reflection: 有几种方法可以在没有反思的情况下获得价值:
string jsonKey = "key2";
string json = "{\"key1\":\"value1\", \"key2\": \"value2\"}";
dynamic d = JObject.Parse(json);
string jsonValue1 = d.Value<string>(jsonKey); // one way
string jsonValue2 = (string)d[jsonKey]; // another way
and like this: 像这样:
JsonValue jsonValue = JsonValue.Parse("{\"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"IDs\": [116, 943, 234, 38793]}");
double width = jsonValue.GetObject().GetNamedNumber("Width");
double height = jsonValue.GetObject().GetNamedNumber("Height");
string title = jsonValue.GetObject().GetNamedString("Title");
JsonArray ids = jsonValue.GetObject().GetNamedArray("IDs");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.