试图通过JSON.net接收JSON

时间:2015-05-14 04:00:19

标签: c# json weather c3

我已经开始构建一个应用程序来获取World Weather Online的潮汐信息,天气信息,地图绘制功能等,但它无法获得JSON响应。

我已经通过NuGet安装了JSON.net,运行的是Windows 8.1。我只能通过将我的JSON URL粘贴到实际的浏览器中来查看数据。然后使用json2sharp的输出创建下面代码的底部。

尝试http://www.codeproject.com/Tips/397574/Use-Csharp-to-get-JSON-Data-from-the-Web-and-Map-iHow 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();
                }
            }
        }
    }
} 

4 个答案:

答案 0 :(得分:1)

网址中缺少协议

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.

}

并且api返回的JSON字符串不正确,它以&#34; rrr&#34;开头。 (在撰写课程时)

答案 1 :(得分: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);

这有效,检查...

答案 2 :(得分: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);

答案 3 :(得分:0)

您使用的网址不正确。

要获得有效的json,您应该使用:

>>> import pprint
>>> pprint.pprint(result)
{'Content-Type': ' multipart/alternative; boundary="----=_Part_3927_12044027.1214951458678"',
 'Date': ' January 25, 2011 3:30:58 PM PDT',
 'Delivery-Date': ' Tue, 25 Jan 2011 15:31:01 -0700',
 'Dkim-Signature': ' v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=gamma; h=domainkey-signature:received:received:message-id:date:from:to :subject:mime-version:content-type; bh=+JqkmVt+sHDFIGX5jKp3oP18LQf10VQjAmZAKl1lspY=; b=F87jySDZnMayyitVxLdHcQNL073DytKRyrRh84GNsI24IRNakn0oOfrC2luliNvdea LGTk3adIrzt+N96GyMseWz8T9xE6O/sAI16db48q4Iqkd7uOiDvFsvS3CUQlNhybNw8m CH/o8eELTN0zbSbn5Trp0dkRYXhMX8FTAwrH0=',
 'Domainkey-Signature': ' a=rsa-sha1; c=nofws; d=gmail.com; s=gamma; h=message-id:date:from:to:subject:mime-version:content-type; b=wkbBj0M8NCUlboI6idKooejg0sL2ms7fDPe1tHUkR9Ht0qr5lAJX4q9PMVJeyjWalH 36n4qGLtC2euBJY070bVra8IBB9FeDEW9C35BC1vuPT5XyucCm0hulbE86+uiUTXCkaB 6ykquzQGCer7xPAcMJqVfXDkHo3H61HM9oCQM=',
 'Envelope-To': ' user@example.com',
 'From': ' Media Temple user (mt.kb.user@gmail.com)',
 'Message Body': ' **The email message body**',
 'Message-Id': ' <c8f49cec0807011530k11196ad4p7cb4b9420f2ae752@mail.gmail.com>',
 'Mime-Version': ' 1.0',
 'Received': ' from :po-out-1718.google.com ([72.14.252.155]:54907) by cl35.gs01.gridserver.com with esmtp (Exim 4.63) (envelope-from <mt.kb.user@gmail.com>) id 1KDoNH-0000f0-RL for user@example.com; Tue, 25 Jan 2011 15:31:01 -0700',
 'Return-Path': ' <mt.kb.user@gmail.com>',
 'Subject': ' article: A sample header',
 'To': ' user@example.com',
 'X-Spam-Level': ' ***',
 'X-Spam-Status': ' score=3.7 tests=DNS_FROM_RFC_POST, HTML_00_10, HTML_MESSAGE, HTML_SHORT_LENGTH version=3.1.7'}

唯一的区别是我拿出了http://api.worldweatheronline.com/free/v2/weather.ashx?q=Campbell%20River&format=json&num_of_days=5&key=xxxxxxxxxxxxxxxxxxxxx