使用JSON.net反序列化大块json数据

时间:2014-10-16 00:36:51

标签: c# json json.net

我正在慢慢学习JSON响应以及如何使用JSON.net处理它们

我可以在这里找到我获得的数据

http://www.bom.gov.au/fwo/IDN60901/IDN60901.95764.json

作为一个例子,我试图从那个json的“通知”部分中提取“版权”信息

我可以成功地将数据拉下来,但我不确定它是否正确反序列化。文本框中没有出现任何内容,我已经定义了在代码中显示数据,但数据被拉下来,因为我可以在第二个文本框中显示原始响应,就像我在颂歌中定义的那样。

你能告诉我我做错了吗

谢谢:)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Runtime.Serialization.Json;
using System.Runtime.Serialization;
using System.Web;
using Newtonsoft.Json.Linq;



namespace RESTTEST2
{
 public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    public class notice
    {
        public string copyright { get; set; }
        public string copyright_url { get; set; }
        public string disclaimer_url { get; set; }
        public string feedback_url { get; set; }


    }



    private void button1_Click(object sender, EventArgs e)
    {
        richTextBox1.Text = "test";
        string url = "http://www.bom.gov.au/fwo/IDN60901/IDN60901.95764.json";

  HttpWebRequest req = WebRequest.Create(url)
                   as HttpWebRequest;
  req.Credentials = CredentialCache.DefaultCredentials;
  req.ContentType = "application/json";

  string result = null;
  using (HttpWebResponse resp = req.GetResponse()
                            as HttpWebResponse)
  {
  StreamReader reader =
  new StreamReader(resp.GetResponseStream());
  result = reader.ReadToEnd();
  richTextBox2.Text = result; 

  var bar = Newtonsoft.Json.JsonConvert.DeserializeObject<notice>(result);
  var bar2 = bar.copyright_url;
  var bar3 = result.ToString();
  richTextBox1.Text = bar2;

  }



  }
    }
}

2 个答案:

答案 0 :(得分:1)

这是一个使用解决方案的dotNetFiddle工作。 https://dotnetfiddle.net/zSLxoI

单击小提琴页面上的“运行”,然后查看控制台输出。

enter image description here

解决方案详情

noticeList根对象中的JSON数组/ C#Observations

请声明您的类,如下所示,并使用JsonConvert.Deserialize上的RootObject,然后从notice RootObjects访问List Observations

我使用http://json2csharp.com/从JSON字符串生成C#类。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Runtime.Serialization.Json;
using System.Runtime.Serialization;
using System.Web;
using Newtonsoft.Json.Linq;



namespace RESTTEST2
{
 public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

public class Notice
{
    public string copyright { get; set; }
    public string copyright_url { get; set; }
    public string disclaimer_url { get; set; }
    public string feedback_url { get; set; }
}

public class Header
{
    public string refresh_message { get; set; }
    public string ID { get; set; }
    public string main_ID { get; set; }
    public string name { get; set; }
    public string state_time_zone { get; set; }
    public string time_zone { get; set; }
    public string product_name { get; set; }
    public string state { get; set; }
}

public class Datum
{
    public int sort_order { get; set; }
    public int wmo { get; set; }
    public string name { get; set; }
    public string history_product { get; set; }
    public string local_date_time { get; set; }
    public string local_date_time_full { get; set; }
    public string aifstime_utc { get; set; }
    public double air_temp { get; set; }
    public double apparent_t { get; set; }
    public string cloud { get; set; }
    public object cloud_base_m { get; set; }
    public int cloud_oktas { get; set; }
    public string cloud_type { get; set; }
    public object cloud_type_id { get; set; }
    public double delta_t { get; set; }
    public double dewpt { get; set; }
    public object gust_kmh { get; set; }
    public object gust_kt { get; set; }
    public double lat { get; set; }
    public double lon { get; set; }
    public object press { get; set; }
    public object press_msl { get; set; }
    public object press_qnh { get; set; }
    public string press_tend { get; set; }
    public string rain_trace { get; set; }
    public int rel_hum { get; set; }
    public string sea_state { get; set; }
    public string swell_dir_worded { get; set; }
    public object swell_height { get; set; }
    public object swell_period { get; set; }
    public string vis_km { get; set; }
    public string weather { get; set; }
    public string wind_dir { get; set; }
    public int wind_spd_kmh { get; set; }
    public int wind_spd_kt { get; set; }
}

public class Observations
{
    public List<Notice> notice { get; set; }
    public List<Header> header { get; set; }
    public List<Datum> data { get; set; }
}

public class RootObject
{
    public Observations observations { get; set; }
}

    private void button1_Click(object sender, EventArgs e)
    {
        richTextBox1.Text = "test";
        string url = "http://www.bom.gov.au/fwo/IDN60901/IDN60901.95764.json";

  HttpWebRequest req = WebRequest.Create(url)
                   as HttpWebRequest;
  req.Credentials = CredentialCache.DefaultCredentials;
  req.ContentType = "application/json";

  string result = null;
  using (HttpWebResponse resp = req.GetResponse()
                            as HttpWebResponse)
  {
  StreamReader reader =
  new StreamReader(resp.GetResponseStream());
  result = reader.ReadToEnd();
  richTextBox2.Text = result; 

  var bar = Newtonsoft.Json.JsonConvert.DeserializeObject<RootObject>(result);
  var bar2 = bar.observations.notice; // this will have the List<notice> 
  // now you can loop through the List<notice> in bar2 and do whatever you want with it's data.
  // var bar3 = result.ToString();
  richTextBox1.Text = bar2;

  }



  }
    }
}

答案 1 :(得分:0)

使用JSON时,您应该执行以下工作流程:

  • 下载JSON字符串
  • 使用工具
  • 从中生成类
  • 反序列化为对象

代码:

using System;
using System.Net;
using System.Windows.Forms;
using Newtonsoft.Json;

namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        public Form1() {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e) {
            string url = @"http://www.bom.gov.au/fwo/IDN60901/IDN60901.95764.json";
            var client = new WebClient();
            var s = client.DownloadString(url);
            var deserializeObject = JsonConvert.DeserializeObject<SampleResponse1>(s);
        }
    }
}

我个人使用JSON C# Class Generator,因为它是一个本地应用程序并且工作得很好,但其他任何东西都可以。

使用此工具生成的类:

using Newtonsoft.Json;

namespace WindowsFormsApplication2
{
    internal class Notice
    {
        [JsonProperty("copyright")]
        public string Copyright { get; set; }

        [JsonProperty("copyright_url")]
        public string CopyrightUrl { get; set; }

        [JsonProperty("disclaimer_url")]
        public string DisclaimerUrl { get; set; }

        [JsonProperty("feedback_url")]
        public string FeedbackUrl { get; set; }
    }

    internal class Header
    {
        [JsonProperty("refresh_message")]
        public string RefreshMessage { get; set; }

        [JsonProperty("ID")]
        public string ID { get; set; }

        [JsonProperty("main_ID")]
        public string MainID { get; set; }

        [JsonProperty("name")]
        public string Name { get; set; }

        [JsonProperty("state_time_zone")]
        public string StateTimeZone { get; set; }

        [JsonProperty("time_zone")]
        public string TimeZone { get; set; }

        [JsonProperty("product_name")]
        public string ProductName { get; set; }

        [JsonProperty("state")]
        public string State { get; set; }
    }

    internal class Datum
    {
        [JsonProperty("sort_order")]
        public int SortOrder { get; set; }

        [JsonProperty("wmo")]
        public int Wmo { get; set; }

        [JsonProperty("name")]
        public string Name { get; set; }

        [JsonProperty("history_product")]
        public string HistoryProduct { get; set; }

        [JsonProperty("local_date_time")]
        public string LocalDateTime { get; set; }

        [JsonProperty("local_date_time_full")]
        public string LocalDateTimeFull { get; set; }

        [JsonProperty("aifstime_utc")]
        public string AifstimeUtc { get; set; }

        [JsonProperty("air_temp")]
        public double AirTemp { get; set; }

        [JsonProperty("apparent_t")]
        public double ApparentT { get; set; }

        [JsonProperty("cloud")]
        public string Cloud { get; set; }

        [JsonProperty("cloud_base_m")]
        public object CloudBaseM { get; set; }

        [JsonProperty("cloud_oktas")]
        public int CloudOktas { get; set; }

        [JsonProperty("cloud_type")]
        public string CloudType { get; set; }

        [JsonProperty("cloud_type_id")]
        public object CloudTypeId { get; set; }

        [JsonProperty("delta_t")]
        public double DeltaT { get; set; }

        [JsonProperty("dewpt")]
        public double Dewpt { get; set; }

        [JsonProperty("gust_kmh")]
        public object GustKmh { get; set; }

        [JsonProperty("gust_kt")]
        public object GustKt { get; set; }

        [JsonProperty("lat")]
        public double Lat { get; set; }

        [JsonProperty("lon")]
        public double Lon { get; set; }

        [JsonProperty("press")]
        public object Press { get; set; }

        [JsonProperty("press_msl")]
        public object PressMsl { get; set; }

        [JsonProperty("press_qnh")]
        public object PressQnh { get; set; }

        [JsonProperty("press_tend")]
        public string PressTend { get; set; }

        [JsonProperty("rain_trace")]
        public string RainTrace { get; set; }

        [JsonProperty("rel_hum")]
        public int RelHum { get; set; }

        [JsonProperty("sea_state")]
        public string SeaState { get; set; }

        [JsonProperty("swell_dir_worded")]
        public string SwellDirWorded { get; set; }

        [JsonProperty("swell_height")]
        public object SwellHeight { get; set; }

        [JsonProperty("swell_period")]
        public object SwellPeriod { get; set; }

        [JsonProperty("vis_km")]
        public string VisKm { get; set; }

        [JsonProperty("weather")]
        public string Weather { get; set; }

        [JsonProperty("wind_dir")]
        public string WindDir { get; set; }

        [JsonProperty("wind_spd_kmh")]
        public int WindSpdKmh { get; set; }

        [JsonProperty("wind_spd_kt")]
        public int WindSpdKt { get; set; }
    }

    internal class Observations
    {
        [JsonProperty("notice")]
        public Notice[] Notice { get; set; }

        [JsonProperty("header")]
        public Header[] Header { get; set; }

        [JsonProperty("data")]
        public Datum[] Data { get; set; }
    }

    internal class SampleResponse1
    {
        [JsonProperty("observations")]
        public Observations Observations { get; set; }
    }
}
相关问题