【发布时间】:2015-11-25 21:08:03
【问题描述】:
我有一个 JObject,我正在从代表自定义对象 Adjuster 的 HTTP 帖子中的 JSON 字符串反序列化它。
然后我将该对象与数据库中已存在的对象合并以创建更新的对象。我这样做是通过反射循环遍历属性并将它们分配到属性名称匹配的位置。
我的问题是无法将 JValue 隐式转换为目标类型,我必须手动转换它。 有没有一种方法可以动态转换对象?我可以获得需要转换为的类型。
这是我的模型绑定器:
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
JObject jsonObj = JsonConvert.DeserializeObject(actionContext.Request.Content.ReadAsStringAsync().Result) as JObject;
Adjuster dbAdjuster = new Adjuster();
Type adjType = dbAdjuster.GetType();
PropertyInfo[] props = adjType.GetProperties();
dbAdjuster = AdjusterFactory.GetAdjuster(Convert.ToInt32(jsonObj["ID"].ToString()));
foreach (var prop in jsonObj.Properties() )
{
foreach (PropertyInfo info in props)
{
if (prop.Name == info.Name && prop.Name != "ID")
{
if (info.GetValue(dbAdjuster) is string)
{
info.SetValue(dbAdjuster, Convert.ToString(prop.Value));
break;
}
//continue for every type
}
else
{
break;
}
}
}
bindingContext.Model = dbAdjuster;
return true;
}
【问题讨论】:
-
AutoMapper 有一个
TypeConverter的接口,它有帮助吗? github.com/AutoMapper/AutoMapper/wiki/Custom-type-converters
标签: c#