AutoMapper – Map a JSON nvarchar(MAX) Field to ViewModel with JSON.NET JArray from Entity Framework
Source Model from Entity Framework public partial class CustomerOrder { public int BusinessEntityID { get; set; } public string OrderDetailsJSON { get; set; } <= JSON nvarchar(MAX) Field from Database Table } Destination Model from Web Application View Model public class CustomerOrderViewModel { public int BusinessEntityID { get; set; } public JArray OrderDetailsJSON { get; set; } <= JSON.NET – JSON Array Property } |
using Newtonsoft.Json; using Newtonsoft.Json.Linq; public static bool IsJSONArray(string strInput) { strInput = strInput.Trim(); if (strInput.StartsWith("[") && strInput.EndsWith("]")) { try { var obj = JArray.Parse(strInput); return true; } catch (JsonReaderException jex) { return false; } catch (Exception ex) { return false; } } else { return false; } } public static bool IsJSONObject(string strInput) { strInput = strInput.Trim(); if (strInput.StartsWith("{") && strInput.EndsWith("}")) { try { var obj = JObject.Parse(strInput); return true; } catch (JsonReaderException jex) { return false; } catch (Exception ex) { return false; } } else { return false; } } |
Define Mapping using AutoMapper; using Newtonsoft.Json.Linq; public class MappingProfile : Profile { protected override void Configure() { CreateMap<CustomerOrder, CustomerOrderViewModel>() .ForMember( d => d.OrderDetailsJSON, e => e.MapFrom(s => ((s.OrderDetailsJSON != null && JSON.IsJSONArray(s.OrderDetailsJSON)) ? JArray.Parse(s.OrderDetailsJSON) : null))); } } |
Mapping Execution CustomerOrderViewModel obj = AutoMapper.Mapper.Map<CustomerOrderViewModel>(item); |