C# Newtonsoft. Json SelectToken не получает значения из API - PullRequest
0 голосов
/ 03 августа 2020

Я пытаюсь запрограммировать консольное приложение, которое будет добывать данные из разных погодных API, записывать их на экран и после сохранять на диск. Я могу отображать значения из Dark Sky, но я не могу получить значения из Open Weather.

Ниже приведен код, начиная с класса

using System;
using System.Collections.Generic;
using System.Text;

namespace WeatherAPIs.Models
{
    class API_URL
    {
        //This Class takes all the relevant values such as latitude, longitude, Barrie city code, API keys, to crate 
        public static string DarkSkyBaseURL = "https://api.darksky.net/forecast/{Key}/44.4074,-79.6567?units=si";
        public static string OpenWeatherBaseURL = "https://api.openweathermap.org/data/2.5/forecast?id=5894171&units=metric&APPID={Key}";
        public static string WeatherBitBaseURL = "https://api.weatherbit.io/v2.0/current?&lat=44.4074&lon=-79.6567&key={Key}";
    }
}

Это основной код:

using System;
using WeatherAPIs.Models;
using System.Net.Http;
using System.Net;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace WeatherAPIs
{
    class API_Data_Mine
    {
        static void Main(string[] args)
        {
            //Defines The client as WebClient and setup the HTTP Header
            using var client = new WebClient();
            client.Headers.Add("User-Agent", "C# Weather API");
            client.Headers.Add("Accept", "application/json");
            client.Headers.Add("Content-Type", "application/json");

            //Download the JSON result from the DarkSkyBaseURL on API_URL Class
            string darkskyresult = client.DownloadString(API_URL.DarkSkyBaseURL);
            var darkskyjson = JsonConvert.DeserializeObject(darkskyresult);
            //Print int the screen the result of the raw and unbeauty JSON download, wait for the user to press a key to resume
            Console.WriteLine(darkskyresult);
            Console.WriteLine("\npress any key to resume.");
            Console.ReadKey();

            string openWResult = client.DownloadString(API_URL.OpenWeatherBaseURL);
            var openWJson = JsonConvert.DeserializeObject(openWResult);
            //Print int the screen the result of the raw and unbeauty JSON download, wait for the user to press a key to resume
            Console.WriteLine(openWResult);
            Console.WriteLine("\npress any key to resume.");
            Console.ReadKey();

            //Parse and beautify the JSON Output from DarkSky URL
            JObject JDarkSKy = JObject.Parse(darkskyresult);
            JObject JopenW = JObject.Parse(openWResult);

            ////Write the beautified JSON from DarkSKy on screen and wait for the user to press a key to exit
            Console.WriteLine(JDarkSKy);
            Console.WriteLine("\nPress any key to resume.");
            Console.ReadKey();

            Console.WriteLine(JopenW);
            Console.WriteLine("\nPress any key to resume.");
            Console.ReadKey();

            ///Mine the JSON selected JSON data and print it on screen

            var DSTemperature = (string)JDarkSKy.SelectToken("currently.temperature");
            var DSPressure = (string)JDarkSKy.SelectToken("currently.pressure");
            var DSWindSpeed = (string)JDarkSKy.SelectToken("currently.windSpeed");
            var DSRealFeel = (string)JDarkSKy.SelectToken("currently.apparentTemperature");
            var DSUvIndex = (string)JDarkSKy.SelectToken("currently.uvIndex");

            var OWTemperature = (string)JopenW.SelectToken("list.main.temp");
            var OWPressure = (string)JopenW.SelectToken("list.main.pressure");
            var OWWindSpeed = (string)JopenW.SelectToken("list.wind.speed");
            var OWRealFeel = (string)JopenW.SelectToken("list.main.feels_like");

            //UV only works wqith paid keys
            //var OWUvIndex = (string)JDarkSKy.SelectToken("list.main.");

            Console.WriteLine("Temperature on Dark Sky is - " + DSTemperature);
            Console.WriteLine("Pressure on Dark Sky is - " + DSPressure);
            Console.WriteLine("Wind Spped on Dark Sky is - " + DSWindSpeed);
            Console.WriteLine("Real Feel on Dark Sky is - " + DSRealFeel);
            Console.WriteLine("Ultra Violet Index on Dark Sky is - " + DSUvIndex);

            Console.WriteLine("Temperature on Open Weather is - " + OWTemperature);
            Console.WriteLine("Pressure on Open Weather is - " + OWPressure);
            Console.WriteLine("Wind Spped on Open Weather is - " + OWWindSpeed);
            Console.WriteLine("Real Feel on Open Weather is - " + OWRealFeel);

            //Console.WriteLine("\nPress any key to resume.");            
            Console.ReadKey();
        }
    }
}

Что мне нужно сделать, чтобы получить данные из Open Weather?

1 Ответ

0 голосов
/ 03 августа 2020

openweathermap возвращает list как массив вместо объекта. Поэтому вам следует соответствующим образом обновить выбранный токен.

Попробуйте использовать [0] для получения данных для первого объекта.

var OWTemperature = (string)JopenW.SelectToken("list[0].main.temp");
var OWPressure = (string)JopenW.SelectToken("list[0].main.pressure");
var OWWindSpeed = (string)JopenW.SelectToken("list[0].wind.speed");
var OWRealFeel = (string)JopenW.SelectToken("list[0].main.feels_like");
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...