如何使用 .NET 4.5.1
使用 HttpClient
库将 JSON
属性值映射到不同名称的模型属性> 框架和 C#
?
我正在使用来自 Weather Underground 的 API,并且我创建了一个控制台应用程序只是为了在迁移到 ASP.NET MVC 5
网络应用程序之前对其进行测试。
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
这样的第三方库。如果无法完成,那么我将查看第 3 方库。
我可能可以拥有与 JSON 中返回的数据属性同名的属性的类,但我喜欢在命名属性时坚持最佳实践,并且属性需要有合适的名称。
最佳答案
也许有点晚了,但供将来引用。
您可以使用 System.Runtime.Serialization 中的 DataMember 属性映射 json 变量名称。将该类标记为 DataContract。请注意,使用这种方法,您想要从 json 字符串映射的每个变量都必须具有 DataMember 属性,而不仅仅是具有自定义映射的变量。
using System.Runtime.Serialization;
[DataContract]
public class Response
{
[DataMember(Name = "conditions")]
public string Terms { get; set; }
[DataMember]
public string Foo { get; set; }
public int Bar { get; set; } // Will not be mapped
}
关于c# - 如何将 JSON 值映射到不同名称的模型属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22296187/