2015-05-14 4 views
1

Я начал создавать приложение, чтобы получать информацию о приливе, информацию о погоде, возможности отображения и т. Д. От World Weather Online, но он не может получить ответ JSON.Пытается получить JSON с JSON.net

Я установил JSON.net через NuGet, работаю под управлением Windows 8.1. Мне удалось даже просмотреть данные, вставив мой URL JSON в фактический браузер. Затем, используя его выход в json2sharp, создадим нижнюю часть моего кода ниже.

Пробные http://www.codeproject.com/Tips/397574/Use-Csharp-to-get-JSON-Data-from-the-Web-and-Map-i и How to get a json string from url?.

using System; 
using System.Net; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 
using GMap.NET.WindowsForms; 
using GMap.NET; 
using GMap.NET.MapProviders; 
using System.Xml.Linq; 
using System.Xml; 
using System.IO; 
using System.Web; 
using Newtonsoft.Json.Linq; 
using Newtonsoft.Json; 
using RestSharp; 
using Newtonsoft.Json.Utilities; 





namespace EOD_Assistant 
{ 


    public partial class Form1 : Form 
    { 

     public Form1() 
     { 
      InitializeComponent(); 



     } 

     private void myMap_Load(object sender, EventArgs e) 
     { 
      myMap.MapProvider = BingHybridMapProvider.Instance; 
      myMap.SetPositionByKeywords("Comox, Canada"); 
      myMap.MinZoom = 1; 
      myMap.MaxZoom = 17; 
      myMap.Zoom = 10; 
      myMap.CanDragMap = true; 
      myMap.MapScaleInfoEnabled = true; 

     } 

     private void Form1_Load(object sender, EventArgs e) 
     { 
      string url = "http://api.worldweatheronline.com/free/v2/weather.ashx?q=Campbell%20River&format=json&num_of_days=5&callback=rrr&key=1ccf49ff57a386e570286ae9294b9"; 

     } 

     private void GetWeather() 
     { 
     } 

     private void weatherBtn_Click(object sender, EventArgs e) 
     { 

     } 

     public class WeatherDesc 
     { 
      public string value { get; set; } 
     } 

     public class WeatherIconUrl 
     { 
      public string value { get; set; } 
     } 

     public class CurrentCondition 
     { 
      public string cloudcover { get; set; } 
      public string FeelsLikeC { get; set; } 
      public string FeelsLikeF { get; set; } 
      public string humidity { get; set; } 
      public string observation_time { get; set; } 
      public string precipMM { get; set; } 
      public string pressure { get; set; } 
      public string temp_C { get; set; } 
      public string temp_F { get; set; } 
      public string visibility { get; set; } 
      public string weatherCode { get; set; } 
      public List<WeatherDesc> weatherDesc { get; set; } 
      public List<WeatherIconUrl> weatherIconUrl { get; set; } 
      public string winddir16Point { get; set; } 
      public string winddirDegree { get; set; } 
      public string windspeedKmph { get; set; } 
      public string windspeedMiles { get; set; } 
     } 

     public class Request 
     { 
      public string query { get; set; } 
      public string type { get; set; } 
     } 

     public class Astronomy 
     { 
      public string moonrise { get; set; } 
      public string moonset { get; set; } 
      public string sunrise { get; set; } 
      public string sunset { get; set; } 
     } 

     public class WeatherDesc2 
     { 
      public string value { get; set; } 
     } 

     public class WeatherIconUrl2 
     { 
      public string value { get; set; } 
     } 

     public class Hourly 
     { 
      public string chanceoffog { get; set; } 
      public string chanceoffrost { get; set; } 
      public string chanceofhightemp { get; set; } 
      public string chanceofovercast { get; set; } 
      public string chanceofrain { get; set; } 
      public string chanceofremdry { get; set; } 
      public string chanceofsnow { get; set; } 
      public string chanceofsunshine { get; set; } 
      public string chanceofthunder { get; set; } 
      public string chanceofwindy { get; set; } 
      public string cloudcover { get; set; } 
      public string DewPointC { get; set; } 
      public string DewPointF { get; set; } 
      public string FeelsLikeC { get; set; } 
      public string FeelsLikeF { get; set; } 
      public string HeatIndexC { get; set; } 
      public string HeatIndexF { get; set; } 
      public string humidity { get; set; } 
      public string precipMM { get; set; } 
      public string pressure { get; set; } 
      public string tempC { get; set; } 
      public string tempF { get; set; } 
      public string time { get; set; } 
      public string visibility { get; set; } 
      public string weatherCode { get; set; } 
      public List<WeatherDesc2> weatherDesc { get; set; } 
      public List<WeatherIconUrl2> weatherIconUrl { get; set; } 
      public string WindChillC { get; set; } 
      public string WindChillF { get; set; } 
      public string winddir16Point { get; set; } 
      public string winddirDegree { get; set; } 
      public string WindGustKmph { get; set; } 
      public string WindGustMiles { get; set; } 
      public string windspeedKmph { get; set; } 
      public string windspeedMiles { get; set; } 
     } 

     public class Weather 
     { 
      public List<Astronomy> astronomy { get; set; } 
      public string date { get; set; } 
      public List<Hourly> hourly { get; set; } 
      public string maxtempC { get; set; } 
      public string maxtempF { get; set; } 
      public string mintempC { get; set; } 
      public string mintempF { get; set; } 
      public string uvIndex { get; set; } 
     } 

     public class Data 
     { 
      public List<CurrentCondition> current_condition { get; set; } 
      public List<Request> request { get; set; } 
      public List<Weather> weather { get; set; } 
     } 

     public class RootObject 
     { 
      public Data data { get; set; } 
     } 

     public class PleaseWORK 
     { 
      private static T _download_serialized_json_data<T>(string url) where T : new() 
      { 
       using (var w = new WebClient()) 
       { 
        var json_data = string.Empty; 
        // attempt to download JSON data as a string 
        try 
        { 
         json_data = w.DownloadString(url); 
        } 
        catch (Exception) { } 
        // if string with JSON data is not empty, deserialize it to class and return its instance 
        return !string.IsNullOrEmpty(json_data) ? JsonConvert.DeserializeObject<T>(json_data) : new T(); 
       } 
      } 
     } 
    } 
} 
+3

Я не уверен, что кастрированный баран вы используете премиум или бесплатную версию, но в в любом случае вы абсолютно не должны делиться своим ключом api. , , (и если это премиальные люди могли бы использовать его, и вы в конечном итоге заплатили) –

+0

Возможно, вам следует уточнить, что происходит не так. Какое исключение выбрасывается и т. Д. –

ответ

1

протокол отсутствует в URL

string url = "http://api.worldweatheronline.com/free/v2/weather.ashx?q=Campbell%20River&format=json&num_of_days=5&callback=rrr&key=xxxxxxxxxxxxxxxxxxxxxxx"; 
using (var webClient = new System.Net.WebClient()) 
{ 
    var json = webClient.DownloadString(url); //THIS GIVES ME AN EXCEPTION ERROR....DUNNO WHY. 

} 

и строку JSON returnd в API не является правильным, он начинается с "RRR" (на момент написания курса)

+0

Большое вам спасибо. Больше никаких ошибок, кроме случаев, когда я не могу заполнить эту информацию. Вернее, я не могу его использовать. Когда я вставляю код для его использования, я получаю сообщение об ошибке. Я пытаюсь назвать это так, когда я нажимаю кнопку погоды var rootObject = _download_serialized_json_data (url); Но это не займет. –

+0

Строка json неверна, она начинается с rrr ... –

0
string url = "http://api.worldweatheronline.com/free/v2/weather.ashx?q=Campbell%20River&format=json&num_of_days=5&callback=rrr&key=1ccf49ff57a386e570286ae9294b9"; 
       var jsonString = web.DownloadString(url).ToString(); 
       var parseJsonString = jsonString.Split('(', ')')[1]; 
       var obj = JsonConvert.DeserializeObject<RootObject>(parseJsonString); 

Это работает, Проверьте это ...

0

Вы можете получить JSON строку таким образом

// httpWebRequest with API URL 
     HttpWebRequest request = (HttpWebRequest)WebRequest.Create 
     ("http://YourURL.com"); 

     //Method GET 
     request.Method = "GET"; 

     //HttpWebResponse for result 
     HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 


     //Mapping of status code 
     if (response.StatusCode == HttpStatusCode.OK) 
     { 
      Stream receiveStream = response.GetResponseStream(); 
      StreamReader readStream = null; 

      if (response.CharacterSet == "") 
       readStream = new StreamReader(receiveStream); 
      else 
       readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet)); 

      //Get news data in json string 
      string data = readStream.ReadToEnd(); 
} 

После этого вы можете преобразовать эту строку в DataSet так же, как это.

DataSet ds = new DataSet(); 
StringReader reader = new StringReader(data); 
ds.ReadXml(reader); 
0

URL, который вы используете, является неправильным.

Чтобы получить действительный JSON, вы должны использовать:

http://api.worldweatheronline.com/free/v2/weather.ashx?q=Campbell%20River&format=json&num_of_days=5&key=xxxxxxxxxxxxxxxxxxxxx 

Единственное отличие состоит в том, что я вынул &callback=rrr

Смежные вопросы