一种好方法是将具有某些属性(其中之一是JSON字符串)的对象自动映射到另一个对象,在该对象中该JSON字符串将由属性而不是JSON表示。
有关示例,请参见下面的源类和目标类:
在此示例中, CustomJson
看起来像这样,但对于其他AlertType类型,可能会有所不同:{ "AlertPrice": 500.0 }
//This is the database table representation (source)
public class Alert
{
public int Id { get; set; }
public int UserId { get; set; }
public string AlertType { get; set; }
public string CustomJson { get; set; }
}
//This is the business logic model (destination)
public class UserAlert
{
public int Id { get; set; }
public int UserId { get; set; }
public string AlertType { get; set; }
//This comes from the CustomJson string in the DB
//A different AlertType may need to map to a different object with different properties
public decimal AlertPrice { get; set; }
}
ValueResolver
会允许我这样做吗,还是只能映射对象的一部分?如果没有,也许我应该只拥有一个包含自定义信息的Custom
属性,而不是尝试将其融合到顶级对象中。
答案 0 :(得分:1)
CreateMap<sourceobject, destobject>()
.AfterMap((src, dest) =>
{
dest.AlertPrice = JsonConvert.DeserializeObject<T>(json).AlertPrice;
});
答案 1 :(得分:0)
CreateMap<sourceobject, destobject().AfterMap((src, dest) =>
{
dest.AlertPrice = decimal.Parse(src.AlertPrice, CultureInfo.InvariantCulture);
});
请使用上面的代码使用显式映射