【发布时间】:2020-03-08 10:36:18
【问题描述】:
我正在做的是将我从 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,city=riga,在预测中,我有 7 个项目,每个工作日都有其他天气数据。
我想要得到的是 YahooWeatherModel 列表,其中包含 7 个元素,包括国家、城市、日、低、高...等信息
【问题讨论】:
-
我不知道你打算如何将
List<T1>扁平化为T2,你当然可以像T2 = List<T1>.First()那样做,但问题是你到底想达到什么目的?预期的最终结果是什么?
标签: c# json mapping automapper