0

I am slowly learning JSON responses and how to handle them with JSON.net

The data i am obtaining can be found here

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

As an example i am trying to pull out the "Copyright" info from the "notice" section of that json

I can successfully pull the data down but i'm not sure its being deserialized properly. Nothing is appearing in the textbox that i have defined to show the data in the code but the data is being pulled down as i can display the raw response in the second textbox as i have defined in the ode.

Can you please let me know what i am doing wrong

Thanks :)

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 Answers 2

1

Here's a working dotNetFiddle with the Solution. https://dotnetfiddle.net/zSLxoI

Click Run on the fiddle page and see the console output.

enter image description here

Solution Details

notice is a JSON array / C# List inside the Observations root object.

So declare your classes like below, and use the JsonConvert.Deserialize on the RootObject and then access the notice List from the Observations RootObjects.

I used http://json2csharp.com/ to generate the C# classes from the JSON string.

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;

  }



  }
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you for your help, but i am still a bit stuck to a degree. I can see that bar2 can now read the notice list but i am still not finding it easy to get the copyright element. For example i've tried var bar9 = bar2.copyright; and that was not correct. How can i actually access the individual data elements now that it seems to have deserialized correctly. Thank you :)
bar2 is a List<notice>, not an individual notice. So you should loop through that list (see the code in the dotNetFiddle link.
thank you sorry i did not originally see the fiddle.
Cool. FYI, I used json2csharp.com to generate the proper classes and nesting (of Lists etc). I updated this in my answer so others can benefit from it :)
0

You should do the following workflow when working with JSON :

  • download the JSON string
  • generate classes from it using a tool
  • deserialize to an object

Code:

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

Personally I use JSON C# Class Generator because it is a local application and works quite well but anything else will do.

Classes generated using this tool :

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.