AutoMapper映射无法正常工作JObject / Json

时间:2018-10-12 07:05:34

标签: c# automapper

我正在尝试使用Automapper将JObject映射到POCO类,它仅映射了相同的name属性,而ignore方法无效。

我不确定AutoMapper是否支持Json到POCO类的映射,还是我的配置有问题?

internal class Program
{
    private static void Main(string[] args)
    {
        AutoMapperConfiguration.Configure();

        string json = File.ReadAllText("jsonData.json");
        JArray assets = JArray.Parse(json);
        List<AssetDTO> assetDTOList = Mapper.Map<List<AssetDTO>>(assets);
    }
}

public class AutoMapperConfiguration
{
    public static void Configure()
    {
        AutoMapper.Mapper.Initialize(x => x.AddProfile<AssetProfile>());
    }
}

public class AssetProfile : Profile
{
    public AssetProfile()
    {
        CreateMap<JObject, AssetDTO>()
            .ForAllMembers(dest => dest.Ignore());

        CreateMap<JObject, AssetDTO>()
            .ForMember(dest => dest.AssetId, o => o.MapFrom(j => j["AssetId"]))
            .ForMember(dest => dest.Type, o => o.MapFrom(j => j["AssetType"]))
            .ForMember(dest => dest.DeviceSerialNumber, o => o.MapFrom(j => JArray.Parse(j["Device"].ToString())[0]["SerialNumber"]));
    }
}

public class AssetDTO
{
    public string AssetId { get; set; }
    public string DeviceSerialNumber { get; set; }
    public string Type { get; set; }
}

jsonData.json

[
{
"AssetType": "Paver",
"AssetId": "PaverId100",
"ContactName": "ContactName",
"Description": "description",
"Device": [
  {
    "Make": "BP02",
    "SerialNumber": "BPPA0001",
    "Ucid": null,
    "Address": {
      "AddressLine1": "address 1",
      "AddressLine2": "add 2",
      "City": "city",
      "State": "B'lore",
      "ZipCode": "124578",
      "Country": "India"
    }
  }
]
}
]

Github回购示例代码

1 个答案:

答案 0 :(得分:0)

目前,我已解决此问题。我观察到的问题是Jarray不能像List和Array一样工作,所以我遍历JArray并将每个JObject转换为POCO。

private static void Main(string[] args)
    {
        AutoMapperConfiguration.Configure();

        string json = File.ReadAllText("jsonData.json");
        JArray assets = JArray.Parse(json);
        List<AssetDTO> assetDTOList = new List<AssetDTO>();

        for (int i = 0; i < assets.Count; i++)
        {
            JObject jObject = JObject.Parse(assets[i].ToString());
            AssetDTO assetDTO = Mapper.Map<AssetDTO>(jObject);
            assetDTOList.Add(assetDTO);
        }

    }

Github回购示例代码