繁体   English   中英

ASP.net mvc API获取请求和JSON数据

[英]ASP.net mvc API get request and JSON data

尝试使用asp.net mvc服务调用天气API。

我有一个类似于这样的Weather类:

public class Weather
{
    public string main { get; set; }
    public string description { get; set; }
}

我用来发出GET请求的方法如下所示:

    async public static Task<List<Weather>> GetWeather()
    {
        List<Weather> weatherData = new List<Weather>();

        HttpClient client = new HttpClient();
        HttpResponseMessage response = await client.GetAsync("http://api.openweathermap.org/data/2.5/weather?lat=35&lon=139&APPID=[MYKEY]");

        HttpContent content = response.Content;

        string data = await content.ReadAsStringAsync();
    }

我正在请求的URI返回JSON对象。

{
  "coord": {
    "lon": 139,
    "lat": 35
  },
  "weather": [
    {
      "id": 804,
      "main": "Clouds",
      "description": "overcast clouds",
      "icon": "04n"
    }
  ],
  "base": "stations",
  "main": {
    "temp": 299.26,
    "pressure": 1007,
    "humidity": 83,
    "temp_min": 296.15,
    "temp_max": 301.15
  },
  "visibility": 16093,
  "wind": {
    "speed": 5.1,
    "deg": 330,
    "gust": 7.2
  },
  "clouds": {
    "all": 90
  },
  "dt": 1533638820,
  "sys": {
    "type": 1,
    "id": 7618,
    "message": 0.0028,
    "country": "JP",
    "sunrise": 1533585473,
    "sunset": 1533634868
  },
  "id": 1851632,
  "name": "Shuzenji",
  "cod": 200
}

我想访问"weather"对象并提取属性maindescription并在我的GetWeather返回一个列表,其中JSON对象的天气属性与我的class Weather中的属性匹配。

我迷失了如何处理字符串data以及如何将JSON数据放入我的List<Weather>

编辑

尝试使用下面的答案中提到的JObject.Parse()但得到一个错误尝试将它打印到控制台时Cannot perform runtime binding on a null reference

async public static Task<List<Weather>> GetWeather()
        {

            HttpClient client = new HttpClient();
            HttpResponseMessage response = await client.GetAsync("http://api.openweathermap.org/data/2.5/weather?lat=35&lon=139&APPID=[MYKEY]");

            HttpContent content = response.Content;

            string data = await content.ReadAsStringAsync();

            dynamic d = JObject.Parse(data);
            var main = d.main.ToString();
            var description = d.description.ToString();

            var weatherData = new List<Weather>
            {
                new Weather { Main = main,
                              Description = description }
            };

            Console.WriteLine(weatherData);

            return weatherData;
        }

从json访问描述值的步骤

为给定的json字符串创建模型类,Visual studio为它提供了选项

编辑 - >粘贴特殊 - >粘贴JSON作为类

上课看起来像

public class MyClass
{
    public class Coord {
       public int lon { get; set; }
       public int 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; } }
 ...

使用NewtonSoft.JSON库反序列化json

MyClass temp = JsonConvert.DeserializeObject<MyClass >(jsonString);

现在您可以访问Weather类的描述属性了

string output = temp.Weather.description

您想要研究反序列化json。 示例的最简单方法(尽管不是可维护的)是将json转储为动态并拉出所需的字段;

dynamic d = JObject.Parse(data);
var description = d.description.ToString();

如果你创建匹配JSON的类(看起来你的Weather类不太匹配 - main是嵌套对象而不是字符串)那么你可以使用Json.DeserializeObject <Weather>(data)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM