Restsharp Issues Deserialising - c#

I'm trying to deserialise a JSON which conatains a series of "Clients" in succession from an API Call:
{"resource":[{"ClientID":1,"ClientName":"Name 1","ClientIntID":"TEST001","ClientCreatedDate":"2018-05-10 00:00:00"},{"ClientID":2,"ClientName":"Name 2","ClientIntID":"TEST002","ClientCreatedDate":"2018-05-10 03:10:47"},{"ClientID":3,"ClientName":"TestAPI","ClientIntID":"API001","ClientCreatedDate":"2018-05-10 03:30:14"},{"ClientID":4,"ClientName":"Postman","ClientIntID":"00POST","ClientCreatedDate":"2018-05-10 05:03:40"},{"ClientID":5,"ClientName":"Postman","ClientIntID":"00POST","ClientCreatedDate":"2018-05-10 05:04:28"},{"ClientID":6,"ClientName":"Postman","ClientIntID":"00POST","ClientCreatedDate":"2018-05-10 05:04:31"},{"ClientID":7,"ClientName":"Postman","ClientIntID":"00POST","ClientCreatedDate":"2018-05-10 05:10:32"},{"ClientID":8,"ClientName":"Postman","ClientIntID":"00POST","ClientCreatedDate":"2018-05-10 05:10:35"}]}
into a List of Clients.
This is my code to deserialise:
IRestResponse<List<Client>> response = restClient.Execute<List<Client>>(request);
var content = response.Content;
var data = response.Data;
//Trying to check output of each Client in List:
foreach(Client c in data)
{
Console.WriteLine(c.ClientName);
}
This is my Client Class:
public class Client
{
public int ClientID { get; set; }
public string ClientName { get; set; }
public string ClientIntID { get; set; }
public string ClientCreatedDate { get; set; }
}
I'm getting a list that is null, however when I change the code to simply cast into one Client only, it correctly stores the first client in the JSON response.
Any tips?

Your answer is in the form of the following format, so you have to deserialize into RootObject
public class Resource {
public int ClientID { get; set; }
public string ClientName { get; set; }
public string ClientIntID { get; set; }
public string ClientCreatedDate { get; set; }
}
public class RootObject{
public List<Resource> resource { get; set; }
}

Related

Problems deserializing Json from MusixMatch API?

I'm trying to implement MusixMatch API, I must admit, when I debug I'm unable to see what's in the ObservableCollection after the API call because the debugger jumps to another thread (I have zero expertise in thread management), however I can see what's the from the API response, Visual Studio says is not Json formatted:
HttpClient httpClient = new HttpClient();
var response = await httpClient.GetStringAsync($"https://api.musixmatch.com/ws/1.1/artist.search?format=jsonp&callback=callback&q_artist=queen&page=1&page_size=5&apikey={apikey}");
RootObject testList= JsonConvert.DeserializeObject<RootObject>(response);
return testList;
I have a model with this structure:
public class Header
{
public int status_code { get; set; }
public double execute_time { get; set; }
public int available { get; set; }
}
public class ArtistNameTranslation
{
public string language { get; set; }
public string translation { get; set; }
}
public class ArtistNameTranslationList
{
public ArtistNameTranslation artist_name_translation { get; set; }
}
public class ArtistAliasList
{
public string artist_alias { get; set; }
}
public class ArtistCredits
{
public List<object> artist_list { get; set; }
}
public class Artist
{
public int artist_id { get; set; }
public string artist_name { get; set; }
public List<ArtistNameTranslationList> artist_name_translation_list { get; set; }
public string artist_comment { get; set; }
public string artist_country { get; set; }
public List<ArtistAliasList> artist_alias_list { get; set; }
public int artist_rating { get; set; }
public string artist_twitter_url { get; set; }
public ArtistCredits artist_credits { get; set; }
public int restricted { get; set; }
public DateTime updated_time { get; set; }
}
public class ArtistList
{
public Artist artist { get; set; }
}
public class Body
{
public List<ArtistList> artist_list { get; set; }
}
public class Message
{
public Header header { get; set; }
public Body body { get; set; }
}
public class RootObject
{
public Message message { get; set; }
}
}
As I said I was able to see what's in the response from the API, you can look at the complete response:
callback({"message":{"header": {"status_code":200,"execute_time":0.043232917785645,"available":6936},"body":{"artist_list":[{"artist":{"artist_id":118,"artist_name":"Queen","artist_name_translation_list":[{"artist_name_translation":{"language":"JA","translation":"\u30af\u30a4\u30fc\u30f3"}}],"artist_comment":"","artist_country":"","artist_alias_list":[{"artist_alias":"\u30af\u30a4\u30fc\u30f3"},{"artist_alias":"Queen + Adam Lambert"}],"artist_rating":99,"artist_twitter_url":"","artist_credits":{"artist_list":[]},"restricted":0,"updated_time":"2015-12-16T15:50:53Z"}},{"artist":{"artist_id":13755603,"artist_name":"Queen with David Bowie","artist_name_translation_list":[{"artist_name_translation":{"language":"EN","translation":"Queen"}}],"artist_comment":"","artist_country":"","artist_alias_list":[{"artist_alias":"Queen"}],"artist_rating":38,"artist_twitter_url":"","artist_credits":{"artist_list":[{"artist":{"artist_id":118,"artist_name":"Queen","artist_name_translation_list":[{"artist_name_translation":{"language":"JA","translation":"\u30af\u30a4\u30fc\u30f3"}}],"artist_comment":"","artist_country":"","artist_alias_list":[{"artist_alias":"\u30af\u30a4\u30fc\u30f3"},{"artist_alias":"Queen + Adam Lambert"}],"artist_rating":99,"artist_twitter_url":"","artist_credits":{"artist_list":[]},"restricted":0,"updated_time":"2015-12-16T15:50:53Z"}},{"artist":{"artist_id":431,"artist_name":"David Bowie","artist_name_translation_list":[{"artist_name_translation":{"language":"JA","translation":"\u30c7\u30f4\u30a3\u30c3\u30c9\u30fb\u30dc\u30a6\u30a4"}}],"artist_comment":"","artist_country":"GB","artist_alias_list":[{"artist_alias":"\u30c7\u30f4\u30a3\u30c3\u30c9\u30fb\u30dc\u30a6\u30a4"},{"artist_alias":"David Robert Jones"},{"artist_alias":"David Jones"},{"artist_alias":"Ziggy Stardust"},{"artist_alias":"\ub370\uc774\ube44\ub4dc \ubcf4\uc704"},{"artist_alias":"\u0414\u044d\u0432\u0438\u0434 \u0411\u043e\u0443\u0438"},{"artist_alias":"Davis Bowie"},{"artist_alias":"Bowie"},{"artist_alias":"\u30c7\u30d3\u30c3\u30c9\u30fb\u30dc\u30a6\u30a4"},{"artist_alias":"David Bowie"},{"artist_alias":"Davie Bowie"},{"artist_alias":"The Thin White Duke"}],"artist_rating":85,"artist_twitter_url":"","artist_credits":{"artist_list":[]},"restricted":0,"updated_time":"2018-10-20T16:37:59Z"}}]},"restricted":0,"updated_time":"2015-12-01T18:35:35Z"}},{"artist":{"artist_id":17057,"artist_name":"Queen Latifah","artist_name_translation_list":[{"artist_name_translation":{"language":"JA","translation":"\u30af\u30a4\u30fc\u30f3\u30fb\u30e9\u30c6\u30a3\u30d5\u30a1"}}],"artist_comment":"","artist_country":"US","artist_alias_list":[{"artist_alias":"\u30af\u30a4\u30fc\u30f3\u30fb\u30e9\u30c6\u30a3\u30d5\u30a1"},{"artist_alias":"Queen Latifa"},{"artist_alias":"Dana Owens"}],"artist_rating":46,"artist_twitter_url":"","artist_credits":{"artist_list":[]},"restricted":0,"updated_time":"2013-11-05T11:25:25Z"}},{"artist":{"artist_id":7321,"artist_name":"Queens of the Stone Age","artist_name_translation_list":[{"artist_name_translation":{"language":"RU","translation":"Queens Of The Stone Age"}}],"artist_comment":"","artist_country":"US","artist_alias_list":[{"artist_alias":"\u30af\u30a4\u30fc\u30f3\u30ba\u30aa\u30d6\u30b6\u30b9\u30c8\u30fc\u30f3\u30a8\u30a4\u30b8"},{"artist_alias":"Queens Of The Stone Age"},{"artist_alias":"shiqishidaihuanghou"},{"artist_alias":"Queen Of Stoneage"},{"artist_alias":"Queens Of The Stoneage"},{"artist_alias":"QOTSA"}],"artist_rating":76,"artist_twitter_url":"https:\/\/twitter.com\/qotsa","artist_credits":{"artist_list":[]},"restricted":0,"updated_time":"2015-12-09T18:04:11Z"}},{"artist":{"artist_id":26029011,"artist_name":"\u5973\u738b\u8702","artist_name_translation_list":[{"artist_name_translation":{"language":"EN","translation":"Queen Bee"}}],"artist_comment":"","artist_country":"JP","artist_alias_list":[{"artist_alias":"Queen Bee"}],"artist_rating":48,"artist_twitter_url":"","artist_credits":{"artist_list":[]},"restricted":0,"updated_time":"2019-07-15T13:55:16Z"}}]}}});
(https://drive.google.com/file/d/1RH9qxrCfKOXdX16eKy74iWhtbnfT46mD/view?usp=sharing)
As I said, Visual Studio is telling me that the response is not in Json>
(https://drive.google.com/file/d/1MoZlKEIbh8Epp_CC9gukWYtMBwp5oXwy/view?usp=sharing)
Looks like you are passing a parameter format=jsonp in the URL. JSONP is a format where JSON data is wrapped in a callback function. It is intended to be used from within <script> tags in HTML pages. If you want plain JSON, try changing that parameter to format=json and removing the corresponding callback parameter. Or you could try removing both format and callback parameters, assuming that JSON is the default format.
If that doesn't work, then the other alternative is to strip off the callback() function wrapper from the response string prior to trying to parse it as JSON. You can do that with a helper method like this:
public static string ExtractJson(string text)
{
int i = text.IndexOf('(');
int j = text.LastIndexOf(')');
return i > -1 && j > i ? text.Substring(i + 1, j - i - 1) : null;
}
You need to update your code to:
var response = await httpClient.GetStringAsync($"https://api.musixmatch.com/ws/1.1/artist.search?format=jsonp&callback=callback&q_artist=queen&page=1&page_size=5&apikey={apikey}");
var contents = await response.Content.ReadAsStringAsync();
RootObject testList= JsonConvert.DeserializeObject<RootObject>(contents);
return testList;

Convert Rest API JSON Response into C# object

I have a code REST API response which is json, and parsing to JObject and pulling a value from it. But i am getting the error when parsing to JObject.
Error: "Unexpected character encountered while parsing value: S. Path '', line 0, position 0."
Is there any other way to convert Json string to C# object.
I have the following code:
using Newtonsoft.Json;
using (HttpResponseMessage message = httpclient.GetAsync(folderIdURL).Result)
{
if(message.IsSuccessStatusCode)
{
var dataobjects = message.Content.ReadAsStringAsync();
//dataobjects = "{"id":"https://gbc-dev5.cloud.wc.com/DctmRest/repositories/dmgbsap_crt/","title":"DQL query results","author":[{"name":"EMC Documentum"}],"updated":"2019-05-02T15:19:52.508+00:00","page":1,"items-per-page":100,"links":[{"rel":"self","href":"https://gbc-dev5.cloud.wc.com/DctmRest/repositories/dmgbsap_crt/?dql=SELECT%20r_object_id%2cobject_name%20FROM%20dm_sysobject%20WHERE%20FOLDER%20(%27%2fgbc%2fUS%2fOSA-ATTACHMENT%2f2019%27)"}],"entries":[{"id":"https://gbc-dev5.cloud.wc.com/DctmRest/repositories/dmgbsap_crt/?dql=SELECT%20r_object_id%2cobject_name%20FROM%20dm_sysobject%20WHERE%20FOLDER%20(%27%2fgbc%2fUS%2fOSA-ATTACHMENT%2f2019%27)&index=0","title":"0b0111738011c114","updated":"2019-05-02T15:19:52.508+00:00","published":"2019-05-02T15:19:52.508+00:00","links":[{"rel":"edit","href":"https://gbc-dev5.cloud.wc.com/DctmRest/repositories/dmgbsap_crt/objects/0b0111738011c114"}],"content":{"json-root":"query-result","definition":"https://gbc-dev5.cloud.wc.com/DctmRest/repositori es/dmgbsap_crt/types/dm_sysobject","properties":{"r_object_id":"0b0111738011c114","object_name":"04"},"links":[{"rel":"self","href":"https://gbc-dev5.cloud.wc.com/DctmRest/repositories/dmgbsap_crt/objects/0b0111738011c114"}]}},{"id":"https://gbc-dev5.cloud.wc.com/DctmRest/repositories/dmgbsap_crt/?dql=SELECT%20r_object_id%2cobject_name%20FROM%20dm_sysobject%20WHERE%20FOLDER%20(%27%2fgbc%2fUS%2fOSA-ATTACHMENT%2f2019%27)&index=1","title":"0b0111738011c115","updated":"2019-05-02T15:19:52.509+00:00","published":"2019-05-02T15:19:52.509+00:00","links":[{"rel":"edit","href":"https://gbc-dev5.cloud.wc.com/DctmRest/repositories/dmgbsap_crt/objects/0b0111738011c115"}],"content":{"json-root":"query-result","definition":"https://gbc-dev5.cloud.wc.com/DctmRest/repositories/dmgbsap_crt/types/dm_sysobject","properties":{"r_object_id":"0b0111738011c115","object_name":"05"},"links":[{"rel":"self","href":"https://gbc-dev5.cloud.wc.com/DctmRest/repositories/dmgbsap_crt/objects/0b0111738011c115"}]}}]}"
JObject responseObj = JObject.Parse(dataobjects.ToString());
String id = (String)responseObj["entries" -->"content"-->"properties"-->"object_name"];
}
}
}
I am expecting the value from (String)responseObject["enteries"]["content"][" properties"]["object_name"]
JObjects are a pain. You could get a sample of the JSON response and paste it into a converter like json2csharp.com. It will generate a class for you which you can then use like so:
Generated Class:
public class MyClass
{
public string SomeProperty { get; set; }
public string AnotherProperty { get; set; }
}
Usage:
if (message.IsSuccessStatusCode)
{
var deserializedObject = JsonConvert.DeserializeObject<MyClass>(response.Content.ReadAsStringAsync().Result);
Console.WriteLine(deserializedObject.SomeProperty);
}
I would suggest to follow those steps:
You need to check that your json is actually a json, because an error says it is not. You can use online tools like this
If possible, avoid JObject and generate real classes. It is not that hard if you know the structure, and you can use another online tools
Modify your code to use classes
so you will have something like:
using System;
using Newtonsoft.Json;
namespace ConsoleApp11
{
class Program
{
public class Message
{
public Enteries enteries { get; set; }
}
public class Enteries
{
public Content content { get; set; }
}
public class Content
{
public Properties properties { get; set; }
}
public class Properties
{
public string object_name { get; set; }
}
static void Main(string[] args)
{
var input = "{\"enteries\":{\"content\":{ \"properties\":{ \"object_name\":\"your value string\"}}}}";
Message msg = JsonConvert.DeserializeObject<Message>(input);
Console.WriteLine(msg?.enteries?.content?.properties?.object_name ?? "no value");
Console.ReadKey();
}
}
}
I hope it helps 😊
Thank you so much for all the help and trips. Finally i am able to get the required value from JSON string.
Here is the Final code json2csharp.com
public class Author
{
public string name { get; set; }
}
public class Link
{
public string rel { get; set; }
public string href { get; set; }
}
public class Link2
{
public string rel { get; set; }
public string href { get; set; }
}
public class Properties
{
public string r_object_id { get; set; }
public string object_name { get; set; }
}
public class Link3
{
public string rel { get; set; }
public string href { get; set; }
}
public class Content
{
public string json_root { get; set; }
public string definition { get; set; }
public Properties properties { get; set; }
public List<Link3> links { get; set; }
}
public class Entry
{
public string id { get; set; }
public string title { get; set; }
public DateTime updated { get; set; }
public DateTime published { get; set; }
public List<Link2> links { get; set; }
public Content content { get; set; }
}
public class RootObject
{
public string id { get; set; }
public string title { get; set; }
public List<Author> author { get; set; }
public DateTime updated { get; set; }
public int page { get; set; }
public int items_per_page { get; set; }
public List<Link> links { get; set; }
public List<Entry> entries { get; set; }
}
Using Newtonsoft.Json
First get the list of entries from the responseObj. Then loop each entries and use LINQ to JSON to get values by property name or index.
You can use Item[Object] index on JObject/JArray and then cast the returned JValue to the type you want
JObject responseObj = JObject.Parse(dataobjects.ToString());
// get JSON result objects into a list
IList<JToken> entries = responseObj ["entries"].Children().ToList();
foreach(JToken entry in entries)
{
string object_name = (string) entry["content"]["properties"]["object_name"];
}

JSON Deserializer returning NULL Values

I am trying to consume a REST API via a C# Console Application and I've got as far as getting the webservice to return the JSON file, with the format:
{"status":200,"result":{"postcode":"SW1W0DT","quality":1,"eastings":528813,"northings":178953,"country":"England","nhs_ha":"London","longitude":-0.145828,"latitude":51.494853,"european_electoral_region":"London","primary_care_trust":"Westminster","region":"London","lsoa":"Westminster 023E","msoa":"Westminster 023","incode":"0DT","outcode":"SW1W","parliamentary_constituency":"Cities of London and Westminster","admin_district":"Westminster","parish":"Westminster, unparished area","admin_county":null,"admin_ward":"Warwick","ccg":"NHS Central London (Westminster)","nuts":"Westminster","codes":{"admin_district":"E09000033","admin_county":"E99999999","admin_ward":"E05000647","parish":"E43000236","parliamentary_constituency":"E14000639","ccg":"E38000031","nuts":"UKI32"}}}
I have created a class AddressInfo which is as follows:
public class AddressInfo {
public string postcode { get; set; }
public int quality { get; set; }
public int eastings { get; set; }
public int northings { get; set; }
public string country { get; set; }
public string nhs_ha { get; set; }
public string admin_county { get; set; }
public string admin_district { get; set; }
public string admin_ward { get; set; }
public double longitude { get; set; }
public double latitude { get; set; }
public string parliamentary_constituency { get; set; }
public string european_electoral_region { get; set; }
public string primary_care_trust { get; set; }
public string region { get; set; }
public string parish { get; set; }
public string lsoa { get; set; }
public string msoa { get; set; }
public string ccg { get; set; }
public string nuts { get; set; }
public object codes { get; set; }
}
The code to call the API and get the values is:
string strJSON = string.Empty;
strJSON = rClient.makeRequest();
Console.Write(strJSON);
AddressInfo AI = new AddressInfo();
AI = Newtonsoft.Json.JsonConvert.DeserializeObject<AddressInfo>(strJSON);
However, when I debug, AI is returning the values as "NULL".
Thanks
Notice that your JSON has a nested structure. The AddressInfo is contained within its result property, it isn't at the top level.
Your actual class structure to deserialize the entire JSON response should look something like this (I've called the class JsonResponse but you can name it whatever you want):
class JsonResponse{
public int status { get; set; }
public AddressInfo result { get; set; }
}
Then deserialize it like this:
JsonResponse res = JsonConvert.DeserializeObject<JsonResponse>(strJSON);
AddressInfo addressInfo = res.result;
You're missing the fact that you need an outer class that has the properties int status and AdressInfo result.
You don't need to create a separate class to deserialize the entire response, this can be done dynamically to achieve desired result:
var source = "(your JSON");
dynamic data = JObject.Parse(source);
var d = JsonConvert.SerializeObject(data.result);
AddressInfo account = JsonConvert.DeserializeObject<AddressInfo>(d);
Your JSON is nested. The result is a nested object. That's why you are experiencing this issue.

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

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