Unable To Parse JSON Response in C# - 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 ?

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;

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;

Related

How to deserialize an object and pass it to a response model

i have a json string that i deserialize as follows.
using (var streamReader = new StreamReader(httpResponsePayment.GetResponseStream()))
{
var data = streamReader.ReadToEnd();
result = JsonConvert.DeserializeObject<TestResponse>(data);
}
the data object looks as follows
"{\"responseCode\":2402,\"responseMessage\":\"hello\",\"amount\":0,\"acquirer\":{\"account\":{\"Number\":\"4587-54884-784848\"},\"Tag\":\"TF1234569775548494\"}}"
i pass this object to my TestResponse class
public class TestResponse
{
public string responseCode { get; set; }
public string responseMessage { get; set; }
public int amount { get; set; }
}
i can pass the above 3 objects correctly. I dont know how to pass the acquirer object to the TestResponse
acquirer = new
{
account= new
{
Number="4587-54884-784848"
},
Tag= "TF1234569775548494"
}
i tried doing something like this
public class TestResponse
{
public string responseCode { get; set; }
public string responseMessage { get; set; }
public int amount { get; set; }
List<Acquirers> acquirer =new List<Acquirers>();
}
public class Acquirers
{
public string Tag { get; set; }
}
also tried
public class TestResponse
{
public string responseCode { get; set; }
public string responseMessage { get; set; }
public int amount { get; set; }
public string Number {get;set;} //returns null
public string Tag {get;set;} // returns null
}
can someone please guide me
class Program
{
static void Main(string[] args)
{
var json = "{\"responseCode\":2402,\"responseMessage\":\"hello\",\"amount\":0,\"acquirer\":{\"account\":{\"Number\":\"4587-54884-784848\"},\"Tag\":\"TF1234569775548494\"}}";
var result = JsonConvert.DeserializeObject<Root>(json);
}
}
public class Account
{
public string Number { get; set; }
}
public class Acquirer
{
public Account account { get; set; }
public string Tag { get; set; }
}
public class Root
{
public int responseCode { get; set; }
public string responseMessage { get; set; }
public int amount { get; set; }
public Acquirer acquirer { get; set; }
}
you can using this link = https://json2csharp.com/
for convert model

Response is null when I used Restsharp library's GET request to access Json data

I am using Restsharp library to do Webservice operations.I tried to access data from the link(http://www.mocky.io/v2/595616d92900003d02cd7191) and print it in Console but I am not getting any response.When I used breakpoints,Response is showing null.Here's my code to get data from the link.
private async void GetItemsFromJSON()
{
IRestClient client = new RestClient("http://www.mocky.io/v2/595616d92900003d02cd7191");
IRestRequest request = new RestRequest(Method.GET);
request.RequestFormat = DataFormat.Json;
try
{
await Task.Run(() =>
{
IRestResponse<List<ItemDetails>> response = client.Execute<List<ItemDetails>>(request);
var Items = SimpleJson.DeserializeObject<ItemDetails>(response.Content);
Console.WriteLine(response.Content);
}
public class ItemDetails
{
public List<Itemschema> items { get; set; }
}
public class Itemschema
{
public int id { get; set; }
public string sku { get; set; }
public string name { get; set; }
public int attribute_set_id { get; set; }
public int price { get; set; }
public int status { get; set; }
public int visibility { get; set; }
public string type_id { get; set; }
public string created_at { get; set; }
public string updated_at { get; set; }
public int weight { get; set; }
}
Am I missing something here?My schema class which corresponds to the Json data is shown above.
I suspect that:
IRestResponse<List<ItemDetails>> response = client.Execute<List<ItemDetails>>(request);
should be:
IRestResponse<ItemDetails> response = client.Execute<ItemDetails>(request);
http://www.mocky.io/v2/595616d92900003d02cd7191 seems to return an items property which contains an array of schemas. That maps closer to ItemDetails than List<ItemDetails>.
This complete sample works, so you may want to compare it with your code:
using System;
using System.Collections.Generic;
using RestSharp;
namespace Test
{
public class ItemDetails
{
public List<Itemschema> items { get; set; }
}
public class Itemschema
{
public int id { get; set; }
public string sku { get; set; }
public string name { get; set; }
public int attribute_set_id { get; set; }
public int price { get; set; }
public int status { get; set; }
public int visibility { get; set; }
public string type_id { get; set; }
public string created_at { get; set; }
public string updated_at { get; set; }
public int weight { get; set; }
}
public class Program
{
static void Main(string[] args)
{
IRestClient client = new RestClient("http://www.mocky.io/v2/595616d92900003d02cd7191");
IRestRequest request = new RestRequest(Method.GET);
request.RequestFormat = DataFormat.Json;
IRestResponse<ItemDetails> response = client.Execute<ItemDetails>(request);
var Items = SimpleJson.DeserializeObject<ItemDetails>(response.Content);
Console.WriteLine(Items.items.Count);
Console.ReadLine();
}
}
}

C# Beginner - Using classes in different from different classes

This is a file called TwitchAPIexample in folder Plugins under project MyFirstBot. The classes and code is below:
using System.Net;
using System.IO;
using Newtonsoft.Json;
namespace MyFirstBot.Plugins
{
public class TwitchAPIexample
{
private const string url = "https://api.twitch.tv/kraken/streams/<channel>";
public bool isTwitchLive;
private static void BuildConnect()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "Get";
request.Timeout = 12000;
request.ContentType = "application/json";
request.Headers.Add("authorization", "<token>");
using (System.IO.Stream s = request.GetResponse().GetResponseStream())
{
using (StreamReader sr = new System.IO.StreamReader(s))
{
var jsonResponse = sr.ReadToEnd();
RootObject r = JsonConvert.DeserializeObject<RootObject>(jsonResponse);
}
}
}
public class Preview
{
public string small { get; set; }
public string medium { get; set; }
public string large { get; set; }
public string template { get; set; }
}
public class Channel
{
public bool mature { get; set; }
public string status { get; set; }
public string broadcaster_language { get; set; }
public string display_name { get; set; }
public string game { get; set; }
public string language { get; set; }
public int _id { get; set; }
public string name { get; set; }
public string created_at { get; set; }
public string updated_at { get; set; }
public bool partner { get; set; }
public string logo { get; set; }
public string video_banner { get; set; }
public string profile_banner { get; set; }
public object profile_banner_background_color { get; set; }
public string url { get; set; }
public int views { get; set; }
public int followers { get; set; }
}
public class Stream
{
public long _id { get; set; }
public string game { get; set; }
public int viewers { get; set; }
public int video_height { get; set; }
public int average_fps { get; set; }
public int delay { get; set; }
public string created_at { get; set; }
public bool is_playlist { get; set; }
public Preview preview { get; set; }
public Channel channel { get; set; }
}
public class RootObject
{
public Stream stream { get; set; }
}
}
}
What I need to do is use the classes in the namespace MyfirstBot.Plugins in a different file under MyFirstBot project file. I have:
using namespace MyFirstBot.Plugins
but I'm not sure how to use the RootObject. I have tried using:
TwitchAPIexample.stream TwitchLive = new TwitchAPIexample.stream()
but I dont really know how to go from there to check the other strings in the JSON, set them equal to strings, basically just how to manipulate everything in the TwitchAPIexample class.
Again I'm a C# Noob so you don't have to write it for me, but if you could explain it or hit me up with a good resource. I have googled and still am confused. OOP isnt my strong suit.
This is as far as I have gotten:
namespace MyFirstBot
{
public class DiscordBot
{
DiscordClient client;
CommandService commands;
TwitchClient TwitchClient;
TwitchAPIexample.Stream TwitchLive = new TwitchAPIexample.Stream();
public DiscordBot()
{
if(TwitchLive.equals(null))
{
//stream is offline
}
}
}
}
I'm not sure this is the best method.
For me it looks like you need to change your architecture a bit. You don't need static method, and you need to create property trough which you'd be able to access RootObject. And you don't really need to nest those classes.
public class TwitchAPIexample
{
private const string url = "https://api.twitch.tv/kraken/streams/<channel>";
public bool IsTwitchLive { get; set; }
public RootObject Root { get; set; }
public TwitchAPIexample()
{
BuildConnect();
}
private void BuildConnect()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "Get";
request.Timeout = 12000;
request.ContentType = "application/json";
request.Headers.Add("authorization", "<token>");
using (System.IO.Stream s = request.GetResponse().GetResponseStream())
{
using (StreamReader sr = new System.IO.StreamReader(s))
{
var jsonResponse = sr.ReadToEnd();
this.Root = JsonConvert.DeserializeObject<RootObject>(jsonResponse);
}
}
}
}
public class Preview
{
public string small { get; set; }
public string medium { get; set; }
public string large { get; set; }
public string template { get; set; }
}
public class Channel
{
public bool mature { get; set; }
public string status { get; set; }
public string broadcaster_language { get; set; }
public string display_name { get; set; }
public string game { get; set; }
public string language { get; set; }
public int _id { get; set; }
public string name { get; set; }
public string created_at { get; set; }
public string updated_at { get; set; }
public bool partner { get; set; }
public string logo { get; set; }
public string video_banner { get; set; }
public string profile_banner { get; set; }
public object profile_banner_background_color { get; set; }
public string url { get; set; }
public int views { get; set; }
public int followers { get; set; }
}
public class Stream
{
public long _id { get; set; }
public string game { get; set; }
public int viewers { get; set; }
public int video_height { get; set; }
public int average_fps { get; set; }
public int delay { get; set; }
public string created_at { get; set; }
public bool is_playlist { get; set; }
public Preview preview { get; set; }
public Channel channel { get; set; }
}
public class RootObject
{
public Stream stream { get; set; }
}
Now you can do next
namespace MyFirstBot
{
public class DiscordBot
{
DiscordClient client;
CommandService commands;
TwitchClient TwitchClient;
TwitchAPIexample twitchLive = new TwitchAPIexample();
public DiscordBot()
{
if(twitchLive.Root == null || twitchLive.Root.Stream == null)
{
//stream is offline
}
}
}
}
So you are accessing the root object using the twitchLive.Root and trough the root you can access your stream twitchLive.Root.Stream

C# JSON Object wont deserialize

So I have been able to get JSON objects for a few things, however this object is quite a bit more complex.
I'm trying to get comments from Reddit.
Here is the method I use:
public async Task<List<string>> GetComments(string currentSubreddit, string topicID)
{
string commentUrl = "http://www.reddit.com/r/" + currentSubreddit + "/comments/" + topicID + "/.json";
List<Comments> commentList = new List<Comments>();
string jsonText = await wc.GetJsonText(commentUrl);
Comments.RootObject deserializeObject = Newtonsoft.Json.JsonConvert.DeserializeObject<Comments.RootObject>(jsonText);
List<string> commentListTest = new List<string>();
//List<string> commentListTest = deserializeObject.data.children[0].data.children;
return commentListTest;
}
This is the GetJsonText method:
public async Task<string> GetJsonText(string url)
{
var request = WebRequest.Create(url);
string text;
request.ContentType = "application/json; charset=utf-8";
var response = (HttpWebResponse)await request.GetResponseAsync();
using (var sr = new StreamReader(response.GetResponseStream()))
{
text = sr.ReadToEnd();
}
return text;
}
And here is a link to the Object: http://pastebin.com/WQ8XXGNA
And a link to the jsonText: http://pastebin.com/7Kh6cA9a
The error returned says this:
An exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in mscorlib.dll but was not handled in user code
Additional information: Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'JuicyReddit.Comments+RootObject' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
I'd appreciate if anybody could help me with figuring out whats wrong with this.
Thanks
There are a few problems with your code actually
public async Task<List<string>> GetComments(string currentSubreddit, string topicID)
You don't need to return a list of string here, u need to return a full object
First rename RootObject in the model to an appropriate name such as "CommentsObject"
So set up your class like so and name it CommentsObject.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace YOURNAMESPACE.Comments
{
public class MediaEmbed
{
}
public class SecureMediaEmbed
{
}
public class Data4
{
public int count { get; set; }
public string parent_id { get; set; }
public List<string> children { get; set; }
public string name { get; set; }
public string id { get; set; }
public string subreddit_id { get; set; }
public object banned_by { get; set; }
public string subreddit { get; set; }
public object likes { get; set; }
public object replies { get; set; }
public bool? saved { get; set; }
public int? gilded { get; set; }
public string author { get; set; }
public object approved_by { get; set; }
public string body { get; set; }
public object edited { get; set; }
public object author_flair_css_class { get; set; }
public int? downs { get; set; }
public string body_html { get; set; }
public string link_id { get; set; }
public bool? score_hidden { get; set; }
public double? created { get; set; }
public object author_flair_text { get; set; }
public double? created_utc { get; set; }
public object distinguished { get; set; }
public object num_reports { get; set; }
public int? ups { get; set; }
}
public class Child2
{
public string kind { get; set; }
public Data4 data { get; set; }
}
public class Data3
{
public string modhash { get; set; }
public List<Child2> children { get; set; }
public object after { get; set; }
public object before { get; set; }
}
public class Replies
{
public string kind { get; set; }
public Data3 data { get; set; }
}
public class Data2
{
public string domain { get; set; }
public object banned_by { get; set; }
public MediaEmbed media_embed { get; set; }
public string subreddit { get; set; }
public object selftext_html { get; set; }
public string selftext { get; set; }
public object likes { get; set; }
public object secure_media { get; set; }
public object link_flair_text { get; set; }
public string id { get; set; }
public SecureMediaEmbed secure_media_embed { get; set; }
public bool clicked { get; set; }
public bool stickied { get; set; }
public string author { get; set; }
public object media { get; set; }
public int score { get; set; }
public object approved_by { get; set; }
public bool over_18 { get; set; }
public bool hidden { get; set; }
public string thumbnail { get; set; }
public string subreddit_id { get; set; }
public object edited { get; set; }
public object link_flair_css_class { get; set; }
public object author_flair_css_class { get; set; }
public int downs { get; set; }
public bool saved { get; set; }
public bool is_self { get; set; }
public string permalink { get; set; }
public string name { get; set; }
public double created { get; set; }
public string url { get; set; }
public object author_flair_text { get; set; }
public string title { get; set; }
public double created_utc { get; set; }
public int ups { get; set; }
public int num_comments { get; set; }
public bool visited { get; set; }
public object num_reports { get; set; }
public object distinguished { get; set; }
public Replies replies { get; set; }
public int? gilded { get; set; }
public string parent_id { get; set; }
public string body { get; set; }
public string body_html { get; set; }
public string link_id { get; set; }
public bool? score_hidden { get; set; }
public int? count { get; set; }
public List<string> children { get; set; }
}
public class Child
{
public string kind { get; set; }
public Data2 data { get; set; }
}
public class Data
{
public string modhash { get; set; }
public List<Child> children { get; set; }
public object after { get; set; }
public object before { get; set; }
}
public class CommentsObject
{
public string kind { get; set; }
public Data data { get; set; }
}
}
Make your namespace correct!
Then handle the request and deserialise into a list of commentobjects: (u can use the webclient instead of httpclient if you want, this is just an example)
private HttpClient client;
public async Task<List<CommentsObject>> GetComments()
{
client = new HttpClient();
var response = await client.GetAsync("http://www.reddit.com/r/AskReddit/comments/1ut6xc.json");
if (response.IsSuccessStatusCode)
{
string json = await response.Content.ReadAsStringAsync();
List<CommentsObject> comments = await JsonConvert.DeserializeObjectAsync<List<CommentsObject>>(json);
return comments;
}
else
{
throw new Exception("Errorhandling message");
}
}
It's not ideal (and not completely an answer but more of a work around) but I created models that mock the reddit response json to make deserialization super easy. I use JsonProperty attributes on my model properties to pretty up the models a bit.
Here are the models
And since my models directly mock the json I can just use json.net's generic deserialize method.

Navigating JSON data in c#

I'm trying to check if a twitch.tv stream is online or not via c#. Currently I have:
private bool checkStream(String chan)
{
using (var w = new WebClient()) {
String json_data = w.DownloadString("https://api.twitch.tv/kraken/streams/" + chan);
JObject stream = JObject.Parse(json_data);
print(json_data); //just for testing purposes
if (stream["stream"] != null)
{
print("YIPPEE");
}
}
return false;
}
Here's the twitch JSON API for what I'm downloading: https://github.com/justintv/Twitch-API/blob/master/v2_resources/streams.md#get-streamschannel
As you can see, if a stream is currently offline, the stream field just says null. But obviously, it's still there, so my if(stream["stream"]!=null) check doesn't work. Never used JSON or Newtonsoft's json.net before, so I'm kind of at a loss for what to do. Thanks in advance for any help!
You need to create a class that you can de-serialize the json to. For instance, if you receive json that looks like this
MyJson = {
Prop1 : "Property1",
Prop2 : "Property2"
}
then you'll need to create a class that acts as a contract between your program and the JSON stream.
public class MyJsonClass{
public string Prop1;
public string Prop2;
public MyJsonClass(){
}
}
Now, you can deserialize the json to your C# class and check it for any null values:
// Create a MyJson class instance by deserializing your json string
string myJsonString = ...//get your json string
MyJsonClass deserialized = JsonConvert.DeserializeObject<MyJsonClass>(myJsonString);
if ( deserialized.Prop1 == null )
//etc etc etc
Here's a full processor for that Json response (Disclaimer: I used http://json2csharp.com/ for this code ) :
public class Links
{
public string channel { get; set; }
public string self { get; set; }
}
public class Links2
{
public string self { get; set; }
}
public class Links3
{
public string stream_key { get; set; }
public string editors { get; set; }
public string subscriptions { get; set; }
public string commercial { get; set; }
public string videos { get; set; }
public string follows { get; set; }
public string self { get; set; }
public string chat { get; set; }
public string features { get; set; }
}
public class Channel
{
public string display_name { get; set; }
public Links3 _links { get; set; }
public List<object> teams { get; set; }
public string status { get; set; }
public string created_at { get; set; }
public string logo { get; set; }
public string updated_at { get; set; }
public object mature { get; set; }
public object video_banner { get; set; }
public int _id { get; set; }
public string background { get; set; }
public string banner { get; set; }
public string name { get; set; }
public string url { get; set; }
public string game { get; set; }
}
public class Stream
{
public Links2 _links { get; set; }
public string broadcaster { get; set; }
public string preview { get; set; }
public long _id { get; set; }
public int viewers { get; set; }
public Channel channel { get; set; }
public string name { get; set; }
public string game { get; set; }
}
public class RootObject
{
public Links _links { get; set; }
public Stream stream { get; set; }
}
and here's how to use it :
bool StreamOnline = false;
using (var w = new WebClient())
{
var jsonData = w.DownloadData("https://api.twitch.tv/kraken/streams/" + + chan);
var s = new DataContractJsonSerializer(typeof(RootObject));
using (var ms = new MemoryStream(jsonData))
{
var obj = (RootObject)s.ReadObject(ms);
StreamOnline = obj.stream == null;
}
}
return StreamOnline;
Please note that you need to reference System.Runtime.Serialization and add using System.Runtime.Serialization.Json; to use DataContractJsonSerializer. If you don't need every detail just make the stream property of type object (in the RootObject class) and check whether it's null or not.
Have you tried this. The HasValues is a bool property that checks if there are child tokens, if its value is null there will not be any child tokens.
if (stream["stream"].HasValues)
{
print("YIPPEE");
}else
{
print("No Stream");
}

Categories