如何使用HttpClient
库将JSON
属性值映射到不同名称的模型属性,使用.NET 4.5.1
框架和C#
编程语言?
我正在使用Weather Underground的API,并创建了一个控制台应用程序来测试它,然后再将其移植到ASP.NET MVC 5
Web应用程序中。
static void Main(string[] args)
{
RunAsync().Wait();
}
static async Task RunAsync()
{
string _address = "http://api.wunderground.com/api/{my_api_key}/conditions/q/CA/San_Francisco.json";
using (var client = new HttpClient())
{
try
{
HttpResponseMessage response = await client.GetAsync(_address);
response.EnsureSuccessStatusCode();
if (response.IsSuccessStatusCode)
{
Condition condition = await response.Content.ReadAsAsync<Condition>();
}
Console.Read();
}
catch (HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ", e.Message);
}
}
}
我的模型类到这里,我需要填充数据:
public class Condition
{
public Response Response { get; set; }
}
public class Response
{
public string Terms { get; set; }
}
我的部分JSON结果:
{
"response": {
"version":"0.1",
"termsofService":"http://www.wunderground.com/weather/api/d/terms.html",
"features": {
"conditions": 1
}
}
}
这是一个非常基本的例子,但是我该如何将JSON返回的termsofservice值映射到我的响应类中的Terms属性呢?如果可能的话,我希望在使用上述库的范围内,而不是解决第三方库,如
JSON.NET
。如果无法完成,则将查看第三方库。我可以创建具有与JSON返回的数据属性相同名称的属性的类,但是我喜欢遵循最佳实践来命名属性,并且这些属性需要具有良好的名称。
Condition condition = await response.Content.ReadAsAsync<Condition>();
- Brendan Vogt