Joe Phillips
Joe Phillips

Reputation: 51110

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

What is a good way is to automap an object with some properties, one of which is a JSON string, to another object where that JSON string would be represented by properties instead of JSON.

See the source and destination classes below for an example:

CustomJson will look something like this for this example but could be different for other 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; }
}

Will a ValueResolver allow me to do this or will it only be able to map part of the object? If not, perhaps I should just have a Custom property which contain the custom info instead of trying to meld it into the top-level object.

Upvotes: 1

Views: 742

Answers (2)

Shilpa Ka
Shilpa Ka

Reputation: 47

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

Upvotes: 1

Shilpa Ka
Shilpa Ka

Reputation: 47

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

Please use above code you have use Explicity Mapping

Upvotes: 0

Related Questions