Keirathi
Keirathi

Reputation: 397

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!

Upvotes: 2

Views: 4684

Answers (3)

Nasreddine
Nasreddine

Reputation: 37858

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.

Upvotes: 1

Bearcat9425
Bearcat9425

Reputation: 1608

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

Upvotes: 0

Daniel Szabo
Daniel Szabo

Reputation: 7281

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

Upvotes: 2

Related Questions