如何将带有 JSON 属性 的对象自动映射到没有 JSON 属性 的对象?

How can I automap an object with a JSON property to an object without a JSON property?

一个好的方法是将具有某些属性的对象(其中一个是 JSON 字符串)自动映射到另一个对象,其中 JSON 字符串将由属性而不是 JSON.

查看下面的源和目标 类 示例:

对于此示例,

CustomJson 看起来像这样,但对于其他 AlertTypes 可能会有所不同:{ "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 属性,而不是试图将其合并到顶级对象中。

CreateMap<sourceobject, destobject().AfterMap((src, dest) =>
            {
                dest.AlertPrice = decimal.Parse(src.AlertPrice, CultureInfo.InvariantCulture);
            });

请使用上面的代码,您已经使用了显式映射

CreateMap<sourceobject, destobject>()
    .AfterMap((src, dest) =>
        {
            dest.AlertPrice = JsonConvert.DeserializeObject<T>(json).AlertPrice;
        });