将 json 复杂对象映射到普通对象

Mapping json complex object to plain object

我正在做的是将我从 YAHOO 天气获得的 JSON 转换为我的 YahooWeatherModel class。

我的 json 反序列化后的对象(我使用 json.net)看起来像这样:

public class WeatherObject
{
    public Location location { get; set; }
    public List<Forecasts> forecasts { get; set; }
}

public class Location
{
    public string country { get; set; }
    public string city { get; set; }
}

public class Forecasts
{
    public string Day { get; set; }
    public string Date { get; set; }
    public string Low { get; set; }
    public string High { get; set; }
    public int Text { get; set; }
    public int Code { get; set; }
}

我需要的是将这个对象转换成这样的东西:

public class YahooWeatherModel
{
    public string Country { get; set; }
    public string City { get; set; }
    public string Day { get; set; }
    public DateTime Date { get; set; }
    public int Low { get; set; }
    public int High { get; set; }
    public int Text { get; set; }
    public int Code { get; set; }
}

我使用 Automapper 进行映射。我了解如何在我的 WeatherObject:

中为位置 class 部分创建地图
var configuration = new MapperConfiguration(cfg => cfg
    .CreateMap<WeatherObject, YahooWeatherModel>()
    .ForMember(dest => dest.Country, opt => opt.MapFrom(map => map.location.country))
    .ForMember(dest => dest.City, opt => opt.MapFrom(map => map.location.city))

但是如何将列表转换为没有列表的纯数据? 例如,在 location 我有 country=latvia,city=riga,在 forecast 中我有 7 个项目用于每个工作日和其他天气数据。

我想要得到的是 YahooWeatherModel 列表,其中包含 7 个元素,包括国家、城市、日期、低、高...等信息

您可以使用 LINQ 执行此操作:

public void Convert(WeatherObject weatherObject)
{
    IEnumerable<YahooWeatherModel> models = from forecast in weatherObject.forecasts
        select new YahooWeatherModel
        {
            Country = weatherObject.location.country,
            City = weatherObject.location.city,
            Code = forecast.Code,
            Date = System.Convert.ToDateTime(forecast.Date),
            Day = forecast.Day,
            High = System.Convert.ToInt32(forecast.High),
            Low = System.Convert.ToInt32(forecast.Low),
            Text = forecast.Text
        };
}