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

时间:2019-11-12 17:03:43

标签: c# json mapping automapper

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

反序列化后的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中为位置类部分创建地图:

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))

但是如何将列表转换为不带列表的纯数据? 例如,在位置中,我有country = latvia,在城市中有riga,在天气预报中,我每个工作日有7个项目,还有其他天气数据。

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

1 个答案:

答案 0 :(得分:1)

您可以使用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
        };
}