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

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

[我正在做的是将从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个元素,包括国家,城市,天,低,高...等信息

c# json mapping automapper
1个回答
0
投票

您可以使用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
        };
}
© www.soinside.com 2019 - 2024. All rights reserved.