简体   繁体   English

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

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

Trying to call a weather API using a service for asp.net mvc. 尝试使用asp.net mvc服务调用天气API。

I have a Weather class that looks like this: 我有一个类似于这样的Weather类:

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

The method I am using to make the GET request looks like this: 我用来发出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();
    }

The URI I'm requesting returns JSON objects. 我正在请求的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
}

I want to access the "weather" object and extract the properties main and description and in my GetWeather return a list where the weather properties from the JSON object match the properties in my class Weather . 我想访问"weather"对象并提取属性maindescription并在我的GetWeather返回一个列表,其中JSON对象的天气属性与我的class Weather中的属性匹配。

I'm lost on what to do with the string data and how to get the JSON data into my List<Weather> . 我迷失了如何处理字符串data以及如何将JSON数据放入我的List<Weather>

EDIT 编辑

Tried to use JObject.Parse() as mentioned in the answer below but get an error Cannot perform runtime binding on a null reference when trying to print it to the console. 尝试使用下面的答案中提到的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;
        }

Steps to access value of description from your json 从json访问描述值的步骤

Create model class for given json string, Visual studio provided option for it 为给定的json字符串创建模型类,Visual studio为它提供了选项

Edit -> Paste special -> Paste JSON As class 编辑 - >粘贴特殊 - >粘贴JSON作为类

class look like 上课看起来像

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

Use NewtonSoft.JSON library to deserialize json 使用NewtonSoft.JSON库反序列化json

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

Now you can access description property of Weather class by 现在您可以访问Weather类的描述属性了

string output = temp.Weather.description

You want to look into deserializing the json. 您想要研究反序列化json。 The easiest way for an example (although not as maintainable) would be to dump the json into a dynamic and pull the fields you want; 示例的最简单方法(尽管不是可维护的)是将json转储为动态并拉出所需的字段;

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

If you create classes to match the JSON (it looks like your Weather class doesn't quite match - main is a nested object and not a string) then you can use Json.DeserializeObject< Weather >(data) 如果你创建匹配JSON的类(看起来你的Weather类不太匹配 - main是嵌套对象而不是字符串)那么你可以使用Json.DeserializeObject <Weather>(data)

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

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