【发布时间】:2015-07-31 07:45:36
【问题描述】:
我正在制作一个电子商务应用程序,我想推荐基于季节的产品。我将如何使用天气 API 来访问用户的当前位置并找出那个地方的气候并相应地向他推荐产品。
【问题讨论】:
标签: e-commerce windows-applications weather-api
我正在制作一个电子商务应用程序,我想推荐基于季节的产品。我将如何使用天气 API 来访问用户的当前位置并找出那个地方的气候并相应地向他推荐产品。
【问题讨论】:
标签: e-commerce windows-applications weather-api
我不知道您使用的是什么编程语言,但假设它是 C#,这里有一些代码:
首先,您必须添加这些类,它们是我使用http://json2csharp.com/ 生成的:
public class Coord
{
public double lon { get; set; }
public double lat { get; set; }
}
public class Weather
{
public int id { get; set; }
public string main { get; set; }
public string description { get; set; }
public string icon { get; set; }
}
public class Main
{
public double temp { get; set; }
public int pressure { get; set; }
public int humidity { get; set; }
public double temp_min { get; set; }
public double temp_max { get; set; }
}
public class Wind
{
public double speed { get; set; }
public double deg { get; set; }
}
public class Clouds
{
public int all { get; set; }
}
public class Sys
{
public int type { get; set; }
public int id { get; set; }
public double message { get; set; }
public string country { get; set; }
public int sunrise { get; set; }
public int sunset { get; set; }
}
public class RootObject
{
public Coord coord { get; set; }
public List<Weather> weather { get; set; }
public string @base { get; set; }
public Main main { get; set; }
public Wind wind { get; set; }
public Rain rain { get; set; }
public Clouds clouds { get; set; }
public int dt { get; set; }
public Sys sys { get; set; }
public int id { get; set; }
public string name { get; set; }
public int cod { get; set; }
}
然后,您可以从 OpenWeatherMap.org 调用 API,并使用 JSON.NET 对其进行反序列化(您可以在 Nuget 上找到该包)请注意,您必须将“YourAppID”替换为您的,这你可以在这里创建:http://openweathermap.org/appid
using (HttpClient client = new HttpClient())
{
using (HttpResponseMessage response = await client.GetAsync(("http://api.openweathermap.org/data/2.5/weather?lat=" + Position.Coordinate.Latitude.ToString() + "&lon=" + Position.Coordinate.Longitude.ToString() + "&APPID=" + YourAppID)))
{
using (Stream stream = response.Content.ReadAsStreamAsync().Result)
{
using (StreamReader reader = new StreamReader(stream))
{
string json = reader.ReadToEnd();
var root = JsonConvert.DeserializeObject<RootObject>(json);
//Here, you write a ton of if statements, such as the following:
if(root.Main.temp > 32)
{
//Suggest a large coat to the user
}
}
}
}
}
【讨论】: