Source Object (JSON, using JSON.NET if it matters):
{
"conum" : 1001,
"name" : "CLN Industries Corporation",
"agencyName" : "Murphy, Holmes & Associates, LLC",
"sAA" : [{
"code" : 247,
"description" : "Mechanic\u0027s lien - Bond to Discharge - Fixed penalty - where principal has posted Performance and Pa"
}, {
"code" : 277,
"description" : "Mechanic\u0027s lien - Bond to Discharge - Open Penalty - where principal has posted Performance and Paym"
}, {
"code" : 505,
"description" : "Indemnity Bonds - Contractor\u0027s Indemnity Against Damages where there is a performance bond and addit"
}
]
}
Destination Object (C#):
public class CorporateRatesInfo
{
public string Conum { get; set; }
public string Name { get; set; }
public string AgencyName { get; set; }
public List<SaaCode> SaaCodes { get; set; }
}
public class SaaCode
{
public string Code { get; set; }
public string Description { get; set; }
}
Automapper config and mappings:
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<JObject, CorporateRatesInfo>();
cfg.AddProfile<CorporateRatesProfile>();
});
//config.AssertConfigurationIsValid();
_mapper = config.CreateMapper();
public class CorporateRatesProfile : Profile
{
protected override void Configure()
{
CreateMap<JObject, CorporateRatesInfo>()
.ForMember("SaaCodes", cfg => { cfg.MapFrom(jo => jo["sAA"]); })
.ForMember("Conum", cfg => { cfg.MapFrom(jo => jo["conum"]); })
.ForMember("Name", cfg => { cfg.MapFrom(jo => jo["name"]); })
.ForMember("AgencyName", cfg => { cfg.MapFrom(jo => jo["agencyName"]); });
}
}
Everything works except for the SaaCodes conversion, where Automapper converts each entry into an empty SaaCode object (all properties set to null).
How/where do I tell automapper how to convert items in that JSON field into its destination type?
Try this out -
Unfortunately, I followed Bookamp's question in newer versions of AutoMapper and struggled to get this working.
My alternative approach for anyone else finding this issue was found on the following source
Example Array
}
Example Profile Configuration
TypeConverter
A report, I wrote simple solution if the field names match you can use Newtonsoft's deserializer inside the mapper extension helper method. I wrote a generic ResolveJson extension method.
which you can then call by using the below