Automapper:Converting JSON to list of objects

前端 未结 3 796
慢半拍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: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>().ConvertUsing();
            var employeeMap = CreateMap();
    
            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>
    {
        public List Convert(JObject source, List destination, ResolutionContext context)
        {
    
            var userList = new List();
            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(token);
                    }
                    userList.Add(result);
                }
            }
    
            return userList;
        }
    }
    

提交回复
热议问题