如何将 JSON 值映射到不同名称的模型属性

问题描述 投票:0回答:1

如何使用

JSON
框架和
HttpClient
库将
.NET 4.5.1
属性值映射到不同名称的模型属性?

我正在使用 Weather Underground 的 API,我创建了一个控制台应用程序只是为了在转向

C#

Web 应用程序之前对其进行测试。


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); } } }

我的部分 JSON 结果:

public class Condition { public Response Response { get; set; } } public class Response { public string Terms { get; set; } }

这是一个非常基本的示例,如何将 JSON 中返回的 termsofservice 值映射到响应类中的 terms 属性?如果可能的话,我想留在上面使用的库的范围内,而不是解析为像
{ "response": { "version":"0.1", "termsofService":"http://www.wunderground.com/weather/api/d/terms.html", "features": { "conditions": 1 } } }

这样的第三方库。如果无法完成,那么我将寻找第 3 方库。


我可能拥有与 JSON 中返回的数据属性同名的属性的类,但我喜欢在命名属性时坚持最佳实践,并且属性需要有合适的名称。

c# json .net c#-4.0
1个回答
14
投票

您可以使用 System.Runtime.Serialization 中的 DataMember 属性映射 json 变量名称。将类标记为 DataContract。请注意,使用这种方法,您想要从 json 字符串映射的每个变量都必须具有 DataMember 属性,而不仅仅是具有自定义映射的变量。

JSON.NET

© www.soinside.com 2019 - 2024. All rights reserved.