在automapper中反序列化动态对象?

问题描述 投票:0回答:1

我从第三方API获取一些数据。在响应中,我得到一个动态的location_info对象

{
  "country_code3": "SE",
  "country_name": "Sweden",
  "city_name": "Malmo",
  "latitude": 86.69,
  "longitude": 173.0551
}

现在我想获取country_name并使用AutoMapper将其映射到属性Country。为此,我想将上面提到的动态JSON反序列化为LocationInfo模型:

public class LocationInfo
{
    public string Country_Name { get; set; }
}

然后AutoMapper将Country_Name映射到Country。这是我尝试过的:

.ForMember(dest => dest.Country, opts => opts.MapFrom(src => JsonConvert.DeserializeObject<LocationInfo>(src.LocationInfo).Country_Name); 

但它没有用,我得到以下异常:

表达式树可能不包含动态操作。

c# asp.net-core automapper
1个回答
0
投票

当您需要在映射中执行某些方法时,可以使用ResolveUsing方法。对于您的情况,它将是:

.ForMember(dest => dest.Country, opts => opts.ResolveUsing(src => JsonConvert.DeserializeObject<LocationInfo>(src.LocationInfo).Country_Name); 
© www.soinside.com 2019 - 2024. All rights reserved.