1

Is it possible to pass in an argument to a dynamic object, so it returns the object required at runtime?

var file = File.ReadAllText("file.json");
dynamic json = JsonConvert.DeserializeObject(file);
var value = GetValue("EnvironmentConfiguration.Environment");

private static string GetValue(string jsonKey) {

   // pass jsonKey somehow here? Something like this...
   return json.(jsonKey);
}

Is this even possible?

EDIT:

Json file:

{
  "EnvironmentConfiguration": 
  {
    "Environment": "local"
  }
}

Assuming we want to get the value "local" from "EnvironmentConfiguration.Environment".

Silent Kay
  • 161
  • 1
  • 9

3 Answers3

2

I would use JObject and the SelectToken method:

var jobject = JObject.Parse(file);

var value = jobject
    .SelectToken("EnvironmentConfiguration.Environment")
    .ToString();
DavidG
  • 113,891
  • 12
  • 217
  • 223
0

You can get your property by using indexer:

return json[jsonKey];
Aman B
  • 2,276
  • 1
  • 18
  • 26
0

You can use Json.NET as follows:

dynamic json = JObject.Parse("{number:5555, str:'myString', array: [1,2,3,4,5]}");
var value1 = json.number;  // get number value -> 5555
var value2 = json.str;     // get string value -> myString
var value3 = json.array.Count;  // get array count value  -> 5
vlada
  • 167
  • 15
  • No, this is if you hardcode "json.number", if you were to create a method, which you didn't hardcode ".number", how would you pass it in as an argument i.e. json.(argument)? Is essentially what i'm asking. – Silent Kay Jan 24 '20 at 16:31