using System.Collections.Generic;
using Newtonsoft.Json.Linq;
public class DynamicCast<T> where T: class, new()
private Property[] _proprties;
_proprties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(x => x.GetSetMethod() != null)
.Where(x => x.GetGetMethod() != null)
var property = new Property
foreach (var attribute in p.GetCustomAttributes(false))
if (attribute.GetType() == typeof(JsonPropertyAttribute))
var jsonProperty = (JsonPropertyAttribute)attribute;
property.Name = jsonProperty.PropertyName;
if (attribute.GetType() == typeof(JsonIgnoreAttribute))
public T Cast(IDictionary<string, object> d)
dynamic d = new ExpandoObject();
public IEnumerable<T> Cast(IEnumerable<JObject> da)
return da.Select(e => Cast(e));
public IEnumerable<T> Cast(IEnumerable<object> da)
if (e is JObject) return Cast((JObject)e);
if (e is IDictionary<string, object>) return Cast((IDictionary<string, object>)e);
public void Fill(IDictionary<string, object> values, T target)
foreach (var property in _proprties)
if (values.TryGetValue(property.Name, out var value))
property.PropertyInfo.SetValue(target, value, null);
public void Fill(JObject values, T target)
foreach (var property in _proprties)
if (values.TryGetValue(property.Name, out var value))
if (value is JValue jvalue)
var propertyValue = Convert.ChangeType(jvalue.Value, property.PropertyInfo.PropertyType);
property.PropertyInfo.SetValue(target, propertyValue, null);
public void Fill(T obj, IDictionary<string, object> target)
foreach (var property in _proprties)
target[property.Name] = property.PropertyInfo.GetValue(obj, null);
public PropertyInfo PropertyInfo;
public string A { get; set; }
[JsonProperty("theArray")]
public dynamic[] TheArray { get; set; }
public static void Test1()
var myCast = new DynamicCast<MyType>();
dynamic dyn = new ExpandoObject();
var myType = myCast.Cast(dyn);
Console.WriteLine(myType.A);
public static void Test2()
var json = "{'theArray':[{'a':'First'},{'a':'Second'}]}";
var jsonTest = JsonConvert.DeserializeObject<JsonTest>(json);
var myCast = new DynamicCast<MyType>();
var myTypes = myCast.Cast(jsonTest).ToArray();
Console.WriteLine(myTypes[0].A);
public static void Main()