0

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

1
  • I am not sure how are you going to flatten List<T1> to T2, you can do smth like T2 = List<T1>.First() of course but the question is what exactly are you trying to achieve ? What is the expected end result ? Commented Nov 12, 2019 at 17:06

1 Answer 1

1

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
        };
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.