简体   繁体   中英

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.

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?

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

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. You can see that it does not expose public property of JSON, hence you cannot get the value.

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");

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