Giả sử bạn có class Person
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
Bạn có data dynamic như sau:
using System.Dynamic;
dynamic expando = new ExpandoObject();
expando.Name = "John Doe";
expando.Age = 30;
expando.Address = new ExpandoObject();
expando.Address.State = "WA";
Console.WriteLine(expando.Address.State);
Cách 1
using ExpandoObjectExample;
using Newtonsoft.Json;
//--your old code
var convertedObject = JsonConvert.DeserializeObject<Person>(JsonConvert.SerializeObject(expando));
Console.WriteLine(convertedObject.Name);
Cách 2
public static TObject ToObject<TObject>(this IDictionary<string, object> someSource, BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public)
where TObject : class, new()
{
Contract.Requires(someSource != null);
TObject targetObject = new TObject();
Type targetObjectType = typeof(TObject);
// Go through all bound target object type properties...
foreach (PropertyInfo property in
targetObjectType.GetProperties(bindingFlags))
{
// ...and check that both the target type property name and its type matches
// its counterpart in the ExpandoObject
if (someSource.ContainsKey(property.Name)
&& property.PropertyType == someSource[property.Name].GetType())
{
property.SetValue(targetObject, someSource[property.Name]);
}
}
return targetObject;
}
Sử dụng
var person = ((ExpandoObject)expando).ToObject<Person>();
Console.WriteLine(person.Name);
Nhận xét
Đăng nhận xét