Reputation: 168
What I am doing is converting JSON that I get from YAHOO weather to my YahooWeatherModel
class.
My json object after deserialisation (I use json.net) looks like this:
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; }
}
what I need is to convert this object to something like this:
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; }
}
I use Automapper for mapping. I understand how to create map for location class part in my 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))
But how can I convert List to plain data without list? For example in location I have country=latvia, city=riga and in forecast I have 7 items for each week day with other weather data.
What I want to get is list of YahooWeatherModel with 7 elements with country, city, day, low, high... etc info
Upvotes: 0
Views: 227
Reputation: 109
You can do this using 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
};
}
Upvotes: 1