Automapper:Converting JSON to list of objects

前端 未结 3 789
慢半拍i
慢半拍i 2020-12-06 02:56

Source Object (JSON, using JSON.NET if it matters):

{
    \"conum\" : 1001,
    \"name\" : \"CLN Industries Corporation\",
    \"agencyName\" : \"Murphy, Hol         


        
相关标签:
3条回答
  • 2020-12-06 03:22

    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.

    public static class MapperExtensions
    {
        public static T ResolveJson<T>(this JObject jobj, string target)
        {
            return JsonConvert.DeserializeObject<T>(jobj.SelectToken(target).ToString());
        }
    }
    

    which you can then call by using the below

    CreateMap<JObject, CorporateRatesInfo>()
        .ForMember(x => x.SaaCodes,m => { m.MapFrom(s => s.ResolveJson<SaaCode>("sAA"));});
    
    0 讨论(0)
  • 2020-12-06 03:27

    Try this out -

    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; }
    }
    
    public class CorporateRatesProfile : Profile
    {
        protected override void Configure()
        {
            CreateMap<JObject, SaaCode>()
                .ForMember("Code", cfg => { cfg.MapFrom(jo => jo["code"]); })
                .ForMember("Description", cfg => { cfg.MapFrom(jo => jo["description"]); });
    
            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"]); });
    
    
        }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
    
            var config = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap<JObject, CorporateRatesInfo>();
                cfg.AddProfile<CorporateRatesProfile>();
            });
    
            //config.AssertConfigurationIsValid();
            var mapper = config.CreateMapper();
    
            var jsonText =  @"
                                {
                                    ""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""
                                        }
                                    ]
                                }
                            ";
    
            var jsonoObj = JObject.Parse(jsonText);
    
            CorporateRatesInfo dto = mapper.Map<CorporateRatesInfo>(jsonoObj);
    
    
    
        }
    }
    
    0 讨论(0)
  • 2020-12-06 03:36

    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

    {
    'Items': [{
        'Id': '1',
        'EmployeeNo': '1001',
        'FirstName': 'Rajat',
        'LastName': 'Kumar',
        'Gender': {
            'Id': '1',
            'ShortName': 'M',
            'FullName': 'Male'
        }
    }, {
        'Id': '2',
        'EmployeeNo': '1003',
        'FirstName': 'Lisa',
        'LastName': 'David',
        'Gender': {
            'Id': '2',
            'ShortName': 'F',
            'FullName': 'Female'
        }
    }]
    

    }

    Example Profile Configuration

                CreateMap<JObject, List<User>>().ConvertUsing<JObjectToUserListConverter>();
            var employeeMap = CreateMap<JToken, User>();
    
            employeeMap.ForMember(x => x.Id, y => y.MapFrom(j => j.SelectToken(".Id")));
            employeeMap.ForMember(x => x.DisplayName, y => y.MapFrom(j => j.SelectToken(".LastName").ToString() + ", " + j.SelectToken(".FirstName").ToString()));
            employeeMap.ForMember(x => x.Gender, y => y.MapFrom(j => j.SelectToken(".Gender.FullName")));
    
            employeeMap.ForMember(x => x.Login, y => y.MapFrom(j => j.SelectToken(".Login")));
    

    TypeConverter

    public class JObjectToUserListConverter : ITypeConverter<JObject, List<User>>
    {
        public List<User> Convert(JObject source, List<User> destination, ResolutionContext context)
        {
    
            var userList = new List<User>();
            var tokenCountItems = source.SelectTokens("Items").Children().Count();
            for (int i = 0; i < tokenCountItems; i++)
                {
                    var token = source.SelectToken($"Items[{i}]");
                    var result = new User();
    
                    if (token != null)
                    {
                        result = context.Mapper.Map<JToken, User>(token);
                    }
                    userList.Add(result);
                }
            }
    
            return userList;
        }
    }
    
    0 讨论(0)
提交回复
热议问题