Alston Antony
Alston Antony

Reputation: 179

Unable To Parse JSON Response in C#

I am trying to parse a whois json response but when I try parse it I get null values.

string html;
string whoisUrl = "https://whois.apitruck.com/:google.com";

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(whoisUrl);
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
    using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.ASCII))
    {
        html = reader.ReadToEnd();
    }
}
Class1 m = JsonConvert.DeserializeObject<Class1>(html);
MessageBox.Show(m.created);

Object

class Class1
{
    public string created { get; set; }
}

can anyone please point what I am doing wrong here ?

Upvotes: 2

Views: 1635

Answers (2)

Jason W
Jason W

Reputation: 13209

Your Class1 doesn't get the value since "created" is part of the "response" and not the root level of the JSON reponse.

You'll either need to use dynamic or create a hierarchy for the classes for a simple fix.

class Class1
{
    public Response Response { get; set; }
}

class Response
{
    public string created { get; set; }
}

Then you can use this:

Class1 m = JsonConvert.DeserializeObject<Class1>(html);
MessageBox.Show(m.Response.created);

UPDATE

Also, here's an example of how to use the dynamic:

var m = JsonConvert.DeserializeObject<dynamic>(html);
DateTime created = (DateTime)m.response.created;

Upvotes: 6

Backs
Backs

Reputation: 24913

There is nice app to convert json to .net class:

public class Registrar
{
    public string id { get; set; }
    public string name { get; set; }
    public object email { get; set; }
    public string url { get; set; }
}

public class Response
{
    public string name { get; set; }
    public string idnName { get; set; }
    public List<string> status { get; set; }
    public List<string> nameserver { get; set; }
    public object ips { get; set; }
    public string created { get; set; }
    public string changed { get; set; }
    public string expires { get; set; }
    public bool registered { get; set; }
    public bool dnssec { get; set; }
    public string whoisserver { get; set; }
    public List<object> contacts { get; set; }
    public Registrar registrar { get; set; }
    public List<string> rawdata { get; set; }
    public object network { get; set; }
    public object exception { get; set; }
    public bool parsedContacts { get; set; }
}

public class RootObject
{
    public int error { get; set; }
    public Response response { get; set; }
}

...

RootObject result = JsonConvert.DeserializeObject<RootObject>(html);
var created = result.response.created;

Upvotes: 3

Related Questions