How to map poco to JSON using Automapper How to map poco to JSON using Automapper json json

How to map poco to JSON using Automapper


I solved it using the ConstructUsing method of AutoMapper.Here is my map

public void CreateMap()    {        Mapper.CreateMap<List<IngestionErrorDataContract>, object[]>()            .ConvertUsing(                errors =>                    {                        int index = 0;                        var list = new List<object>();                        errors.ForEach(e => list.Add(                            new                                {                                    i = index++,                                    cell = new[]                                               {                                                   e.IngestionErrorId.ToString(),                                                   e.RunId.ToString(),                                                   e.ProcessDate.ToShortDateString(),                                                   e.Status,                                                   e.ErrorDetails                                               }                                }));                        return list.ToArray();                    });    }

and here is my action method now

public virtual ActionResult AllErrors(string sidx, string sord, int page=1, int rows=10)    {        var pageSize = rows;        var pageNumber = page;        var orderBy = string.Format("{0} {1}", sidx, sord);        var result = errorService.GetPagedOpenErrors(pageSize, page, orderBy);        var errors = new List<IngestionErrorDataContract>(result.IngestionErrors);        var totalPages = (int) Math.Ceiling(result.TotalRows/(float) pageSize);        var jsonData = new                           {                               total = totalPages,                               page = pageNumber,                               records = result.TotalRows,                               rows = mapper.Map<List<IngestionErrorDataContract>,object[]>(errors)                           };        return Json(jsonData, JsonRequestBehavior.AllowGet);    }

Much better I think