I’m working on a feature that updates button colors depending on whether a content creator is currently broadcasting. I can successfully retrieve the JSON response and store it in a variable, but I’m struggling with the next steps.
My goal is to check if the “stream” field in the API response is null (which indicates the broadcaster is offline). However, I’m not sure how to properly implement this check.
Here’s my current implementation for the button click event that fetches updated information:
private void UpdateStatus_Click(object sender, RoutedEventArgs e)
{
string apiUrl = @"https://api.twitch.tv/kraken/streams/streamername?client_id=abc123def456";
var jsonResponse = new WebClient().DownloadString(apiUrl);
StreamData data = JsonConvert.DeserializeObject<StreamData>(jsonResponse);
Console.WriteLine(data.streamInfo);
if (data.streamInfo.category == "Call of Duty")
{
StatusButton.Background = Brushes.Green;
}
}
The JSON parsing works fine and data.streamInfo returns the correct information, but I can’t figure out how to determine the live status. Any suggestions on how to properly check this condition?
make sure to check if data.streamInfo is null first. You could do something like if(data.streamInfo != null) { // streamer is online } otherwise, they’re offline. oh, and fyi, the Kraken API is deprecated, so consider moving to the Helix API when possible!
Wrap your WebClient call in a try-catch block - network requests fail all the time. The Twitch API throws errors, connections drop, and your app will crash without proper handling. I’d actually switch to HttpClient instead. It’s newer and handles async way better than WebClient. The null checking advice above is solid, but don’t forget to dispose your WebClient properly. Use a using statement or call Dispose() manually - otherwise you’ll get memory leaks. Found this out the hard way when my app kept eating more RAM during testing.
You can simplify the check by first verifying if data.streamInfo is null. If it is, that means the streamer is offline. Your current implementation only evaluates the category when the streamer is live, so ensure to handle the offline scenario as well. Here’s how you could structure that:
if (data.streamInfo != null)
{
// Streamer is live
if (data.streamInfo.category == "Call of Duty")
{
StatusButton.Background = Brushes.Green;
}
else
{
StatusButton.Background = Brushes.Yellow; // Live but different game
}
}
else
{
// Streamer is offline
StatusButton.Background = Brushes.Red;
}
This approach effectively manages all situations: offline, live with the target game, and live with another game.