Get value of c# dynamic property via string
Once you have your PropertyInfo
(from GetProperty
), you need to call GetValue
and pass in the instance that you want to get the value from. In your case:
d.GetType().GetProperty("value2").GetValue(d, null);
How to get property value of a dynamic type where property name is in a variable in C#
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
C# accessing property values dynamically by property name
public static object ReflectPropertyValue(object source, string property)
{
return source.GetType().GetProperty(property).GetValue(source, null);
}
Get property value from string using reflection
public static object GetPropValue(object src, string propName)
{
return src.GetType().GetProperty(propName).GetValue(src, null);
}
Of course, you will want to add validation and whatnot, but that is the gist of it.
Get properties of a Dynamic Type
You can use reflection to get the properties out and convert it to a dictionary:
dynamic v = new { A = "a" };
Dictionary<string, object> values = ((object)v)
.GetType()
.GetProperties()
.ToDictionary(p => p.Name, p => p.GetValue(v));
Get value of property in nested object using only a string to navigate the object
I found a nuget package to do exactly what i wanted. https://github.com/Domysee/Pather.CSharp
Load class dynamically get property values one of which is a class
This will do the job - please feel free to provide feedback if something does not work as expected.
I first wanted to use a JsonPath query to find the matching children - but it does not seem to support wildcards for property names. At least I did not find any documentation.
Thus we loop through all child properties to find the ones starting with "season/" - this should be fine from a performance perspective as JsonPath probably would do the same and with that small amount of data it doesn't really matter on a modern system anyways.
static IReadOnlyList<SeasonDetails> GetSeasons(string json)
{
List<SeasonDetails> seasons = new List<SeasonDetails>();
JObject jObject = JObject.Parse(json);
foreach (var child in jObject.Children<JProperty>())
{
if (!child.Name.StartsWith("season/"))
{
continue;
}
seasons.Add(child.Value.ToObject<SeasonDetails>());
}
return seasons;
}
public class SeasonDetails
{
public string _id { get; set; }
public string air_date { get; set; }
public Episode[] episodes { get; set; }
public string name { get; set; }
public string overview { get; set; }
public string poster_path { get; set; }
public int season_number { get; set; }
}
public class Episode
{
public string air_date { get; set; }
public int episode_number { get; set; }
public int id { get; set; }
public string name { get; set; }
public string overview { get; set; }
public string production_code { get; set; }
public int season_number { get; set; }
public string still_path { get; set; }
public float vote_average { get; set; }
public int vote_count { get; set; }
}
Afterwards you can do your logic by looping through the list of seasons:
foreach(SeasonDetails season in seasons) {
// Fill your datatable.
}
C# how Set property dynamically by string?
You're trying to set get a property named "ContractType"
on _cotreport
and set it's value with on _cotreport.Contract
. That's not going to work for two reasons.
- The property name (from what I can tell in your code) is
Contract
notContractType
. - You need to set the value on
_cotreport
.
Try this instead
System.Reflection.PropertyInfo property = _cotreport.GetType().GetProperty("Contract");
property.SetValue(_cotreport, COTReportHelper.ContractType.Gold, new object[0]);
If you want to set the enum value by name, that's a separate issue. Try this
var enumValue = Enum.Parse(typeof(COTReportHelper.ContractType), "Gold");
property.SetValue(_cotreport, enumValue, new object[0]);
Related Topics
Casting List<T> - Covariance/Contravariance Problem
MVC Web API: No 'Access-Control-Allow-Origin' Header Is Present on the Requested Resource
Getting All Controllers and Actions Names in C#
Suppress Warning Cs1998: This Async Method Lacks 'Await'
In .Net/C# Test If Process Has Administrative Privileges
How to Best Implement Equals for Custom Types
JSON.Net Cast Error When Serializing Mongo Objectid
How to Set Value for Property of an Anonymous Object
How to Read Regex Captures in C#
Why Are Subjects Not Recommended in .Net Reactive Extensions
Enable Entity Framework 6 for MySQL (C#) in Winforms of Microsoft Visual Studio 2013
How to Make Method Call Another One in Classes
.Contains() on a List of Custom Class Objects
I Need a Event to Detect Internet Connect/Disconnect