【问题标题】:Mapping json complex object to plain object将json复杂对象映射到普通对象
【发布时间】: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&lt;T1&gt; 扁平化为T2,你当然可以像T2 = List&lt;T1&gt;.First() 那样做,但问题是你到底想达到什么目的?预期的最终结果是什么?

标签: c# json mapping automapper


【解决方案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
        };
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-27
    • 1970-01-01
    • 1970-01-01
    • 2019-05-27
    • 2018-07-28
    • 2014-11-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多