Trying to receive JSON with JSON.net - c#

I've started building an app to get tide info, weather info, mapping capabilities, etc from World Weather Online, but it can't get the JSON response.
I've installed JSON.net via NuGet, am running Windows 8.1. I've only been able to even view the data by pasting my JSON URL into an actual browser. Then using its output at json2sharp to create the bottom part of my code below.
Tried http://www.codeproject.com/Tips/397574/Use-Csharp-to-get-JSON-Data-from-the-Web-and-Map-i and How to get a json string from url?.
using System;
using System.Net;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using GMap.NET.WindowsForms;
using GMap.NET;
using GMap.NET.MapProviders;
using System.Xml.Linq;
using System.Xml;
using System.IO;
using System.Web;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using RestSharp;
using Newtonsoft.Json.Utilities;
namespace EOD_Assistant
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void myMap_Load(object sender, EventArgs e)
{
myMap.MapProvider = BingHybridMapProvider.Instance;
myMap.SetPositionByKeywords("Comox, Canada");
myMap.MinZoom = 1;
myMap.MaxZoom = 17;
myMap.Zoom = 10;
myMap.CanDragMap = true;
myMap.MapScaleInfoEnabled = true;
}
private void Form1_Load(object sender, EventArgs e)
{
string url = "http://api.worldweatheronline.com/free/v2/weather.ashx?q=Campbell%20River&format=json&num_of_days=5&callback=rrr&key=1ccf49ff57a386e570286ae9294b9";
}
private void GetWeather()
{
}
private void weatherBtn_Click(object sender, EventArgs e)
{
}
public class WeatherDesc
{
public string value { get; set; }
}
public class WeatherIconUrl
{
public string value { get; set; }
}
public class CurrentCondition
{
public string cloudcover { get; set; }
public string FeelsLikeC { get; set; }
public string FeelsLikeF { get; set; }
public string humidity { get; set; }
public string observation_time { get; set; }
public string precipMM { get; set; }
public string pressure { get; set; }
public string temp_C { get; set; }
public string temp_F { get; set; }
public string visibility { get; set; }
public string weatherCode { get; set; }
public List<WeatherDesc> weatherDesc { get; set; }
public List<WeatherIconUrl> weatherIconUrl { get; set; }
public string winddir16Point { get; set; }
public string winddirDegree { get; set; }
public string windspeedKmph { get; set; }
public string windspeedMiles { get; set; }
}
public class Request
{
public string query { get; set; }
public string type { get; set; }
}
public class Astronomy
{
public string moonrise { get; set; }
public string moonset { get; set; }
public string sunrise { get; set; }
public string sunset { get; set; }
}
public class WeatherDesc2
{
public string value { get; set; }
}
public class WeatherIconUrl2
{
public string value { get; set; }
}
public class Hourly
{
public string chanceoffog { get; set; }
public string chanceoffrost { get; set; }
public string chanceofhightemp { get; set; }
public string chanceofovercast { get; set; }
public string chanceofrain { get; set; }
public string chanceofremdry { get; set; }
public string chanceofsnow { get; set; }
public string chanceofsunshine { get; set; }
public string chanceofthunder { get; set; }
public string chanceofwindy { get; set; }
public string cloudcover { get; set; }
public string DewPointC { get; set; }
public string DewPointF { get; set; }
public string FeelsLikeC { get; set; }
public string FeelsLikeF { get; set; }
public string HeatIndexC { get; set; }
public string HeatIndexF { get; set; }
public string humidity { get; set; }
public string precipMM { get; set; }
public string pressure { get; set; }
public string tempC { get; set; }
public string tempF { get; set; }
public string time { get; set; }
public string visibility { get; set; }
public string weatherCode { get; set; }
public List<WeatherDesc2> weatherDesc { get; set; }
public List<WeatherIconUrl2> weatherIconUrl { get; set; }
public string WindChillC { get; set; }
public string WindChillF { get; set; }
public string winddir16Point { get; set; }
public string winddirDegree { get; set; }
public string WindGustKmph { get; set; }
public string WindGustMiles { get; set; }
public string windspeedKmph { get; set; }
public string windspeedMiles { get; set; }
}
public class Weather
{
public List<Astronomy> astronomy { get; set; }
public string date { get; set; }
public List<Hourly> hourly { get; set; }
public string maxtempC { get; set; }
public string maxtempF { get; set; }
public string mintempC { get; set; }
public string mintempF { get; set; }
public string uvIndex { get; set; }
}
public class Data
{
public List<CurrentCondition> current_condition { get; set; }
public List<Request> request { get; set; }
public List<Weather> weather { get; set; }
}
public class RootObject
{
public Data data { get; set; }
}
public class PleaseWORK
{
private static T _download_serialized_json_data<T>(string url) where T : new()
{
using (var w = new WebClient())
{
var json_data = string.Empty;
// attempt to download JSON data as a string
try
{
json_data = w.DownloadString(url);
}
catch (Exception) { }
// if string with JSON data is not empty, deserialize it to class and return its instance
return !string.IsNullOrEmpty(json_data) ? JsonConvert.DeserializeObject<T>(json_data) : new T();
}
}
}
}
}

Protocol is missing in the url
string url = "http://api.worldweatheronline.com/free/v2/weather.ashx?q=Campbell%20River&format=json&num_of_days=5&callback=rrr&key=xxxxxxxxxxxxxxxxxxxxxxx";
using (var webClient = new System.Net.WebClient())
{
var json = webClient.DownloadString(url); //THIS GIVES ME AN EXCEPTION ERROR....DUNNO WHY.
}
and the JSON string returnd by the api is not correct, it starts with "rrr" (at the time of writing of course)

string url = "http://api.worldweatheronline.com/free/v2/weather.ashx?q=Campbell%20River&format=json&num_of_days=5&callback=rrr&key=1ccf49ff57a386e570286ae9294b9";
var jsonString = web.DownloadString(url).ToString();
var parseJsonString = jsonString.Split('(', ')')[1];
var obj = JsonConvert.DeserializeObject<RootObject>(parseJsonString);
This works, Check it...

You can get JSON string in this way
// httpWebRequest with API URL
HttpWebRequest request = (HttpWebRequest)WebRequest.Create
("http://YourURL.com");
//Method GET
request.Method = "GET";
//HttpWebResponse for result
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
//Mapping of status code
if (response.StatusCode == HttpStatusCode.OK)
{
Stream receiveStream = response.GetResponseStream();
StreamReader readStream = null;
if (response.CharacterSet == "")
readStream = new StreamReader(receiveStream);
else
readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));
//Get news data in json string
string data = readStream.ReadToEnd();
}
After that you can convert that string to DataSet also like this.
DataSet ds = new DataSet();
StringReader reader = new StringReader(data);
ds.ReadXml(reader);

The URL you're using is not correct.
To get valid json, you should use :
http://api.worldweatheronline.com/free/v2/weather.ashx?q=Campbell%20River&format=json&num_of_days=5&key=xxxxxxxxxxxxxxxxxxxxx
The only difference is that i took out the &callback=rrr

Related

C# Deserialize json api response

hey i want to Deserialize this json API response to get values including profile state etc for processing in the program.
i tried multiple ways from different questions in here but i get response as null.
here is the code, correct me what i am doing wrong please
{
"response": {
"players": [{
"steamid": "xxxxxxxxxxxxxxxxx",
"communityvisibilitystate": 3,
"profilestate": 1,
"personaname": "xxxx xxxx",
"lastlogoff": 1529478555,
"commentpermission": 1,
"profileurl": "xxxxxxxxxxxxxxx",
"avatar": "xxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"avatarmedium": "xxxxxxxxxxxxxxxxxxxxx",
"avatarfull": "xxxxxxxxxxx",
"personastate": 1,
"realname": "xxxx",
"primaryclanid": "xxxxxxxxxx",
"timecreated": 1097464215,
"personastateflags": 0
}]
}
}
The code i tried
public class AccountInfo
{
public string steamid { get; set; }
public int communityvisibilitystate { get; set; }
public int profilestate { get; set; }
public string personaname { get; set; }
public ulong lastlogoff { get; set; }
public int commentpermission { get; set; }
public string profileurl { get; set; }
public string avatar { get; set; }
public string avatarmedium { get; set; }
public string avatarfull { get; set; }
public int personastate { get; set; }
public string realname { get; set; }
public string primaryclanid { get; set; }
public ulong timecreated { get; set; }
public int personastateflags { get; set; }
}
public class Response
{
public AccountInfo response { get; set; }
}
public class Response1
{
public Response players { get; set; }
}
static void Main(string[] args)
{
DeserilizeJson();
}
internal static void DeserilizeJson()
{
string json = GetUrlToString("http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=xxxxxxxxxxxxxxxxxxxxx&steamids=xxxxxxxxxxxxxxx");
Console.WriteLine(json);
Response1 info = JsonConvert.DeserializeObject<Response1>(json);
using (StreamWriter file = File.CreateText(#"c:\test.json"))
{
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(file, info);
}
}
internal static string GetUrlToString(string url)
{
String Response = null;
try
{
using (WebClient client = new WebClient())
{
Response = client.DownloadString(url);
}
}
catch (Exception)
{
return null;
}
return Response;
}
Use this as a Model Class
using System;
using System.Collections.Generic;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
public partial class JsonModel
{
[JsonProperty("response")]
public Response Response { get; set; }
}
public partial class Response
{
[JsonProperty("players")]
public List<Player> Players { get; set; }
}
public partial class Player
{
[JsonProperty("steamid")]
public string Steamid { get; set; }
[JsonProperty("communityvisibilitystate")]
public long Communityvisibilitystate { get; set; }
[JsonProperty("profilestate")]
public long Profilestate { get; set; }
[JsonProperty("personaname")]
public string Personaname { get; set; }
[JsonProperty("lastlogoff")]
public long Lastlogoff { get; set; }
[JsonProperty("commentpermission")]
public long Commentpermission { get; set; }
[JsonProperty("profileurl")]
public string Profileurl { get; set; }
[JsonProperty("avatar")]
public string Avatar { get; set; }
[JsonProperty("avatarmedium")]
public string Avatarmedium { get; set; }
[JsonProperty("avatarfull")]
public string Avatarfull { get; set; }
[JsonProperty("personastate")]
public long Personastate { get; set; }
[JsonProperty("realname")]
public string Realname { get; set; }
[JsonProperty("primaryclanid")]
public string Primaryclanid { get; set; }
[JsonProperty("timecreated")]
public long Timecreated { get; set; }
[JsonProperty("personastateflags")]
public long Personastateflags { get; set; }
}
Then do this in your Main Class
var info = JsonConvert.DeserializeObject<JsonModel>(json);
var Response = info.Response
Open nuget, search newtonsoft.json and install.
Deserialize:
var deserialized = JsonConvert.DeserializeObject(jsonstring);
Try this:
public class Player
{
public string steamid { get; set; }
public int communityvisibilitystate { get; set; }
public int profilestate { get; set; }
public string personaname { get; set; }
public ulong lastlogoff { get; set; }
public int commentpermission { get; set; }
public string profileurl { get; set; }
public string avatar { get; set; }
public string avatarmedium { get; set; }
public string avatarfull { get; set; }
public int personastate { get; set; }
public string realname { get; set; }
public string primaryclanid { get; set; }
public ulong timecreated { get; set; }
public int personastateflags { get; set; }
}
public class Response
{
public Player[] players { get; set; }
}
public class EncapsulatedResponse
{
public Response response {get;set;}
}
internal static void DeserilizeJson()
{
string json = GetUrlToString("http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=xxxxxxxxxxxxxxxxxxxxx&steamids=xxxxxxxxxxxxxxx");
Console.WriteLine(json);
EncapsulatedResponse info = JsonConvert.DeserializeObject<EncapsulatedResponse>(json);
using (StreamWriter file = File.CreateText(#"c:\test.json"))
{
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(file, info);
}
}
The players property should be a list of players as it is an array . Below is the Correct Model
public class Player
{
public string steamid { get; set; }
public int communityvisibilitystate { get; set; }
public int profilestate { get; set; }
public string personaname { get; set; }
public int lastlogoff { get; set; }
public int commentpermission { get; set; }
public string profileurl { get; set; }
public string avatar { get; set; }
public string avatarmedium { get; set; }
public string avatarfull { get; set; }
public int personastate { get; set; }
public string realname { get; set; }
public string primaryclanid { get; set; }
public int timecreated { get; set; }
public int personastateflags { get; set; }
}
public class Response
{
public List<Player> players { get; set; }
}
You need to change the object structure:
public class Response
{
public AccountInfo[] players { get; set; }
}
public class Response1
{
public Response response { get; set; }
}
then deserialize Response1 (like u do currently)
Just to provide a different approach, you can use JObject (Newtonsoft.Json.Linq) so that you only need the AccountInfo class:
var accounts = JObject.Parse(json).Root
.SelectToken("response.players")
.ToObject(typeof(AccountInfo[]));
Or in some cases, it is even easier just navigating the properties:
var accounts = JObject.Parse(json)["response"]["players"]
.ToObject((typeof(AccountInfo[])));

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

JSON deserialization not deserializing?

I am bit new to the serialization/deserialization of JSON's strings. I have tried to use Newtonsoft.Json. The thing is I got JSON string received from
url : http://epguides.frecar.no/show/gameofthrones/ and I would like to create and class objects from it. So later I could print it out...
I found out how to generate classes from your JSON string, by copying the string and Edit>Paste_Special>Paste_JSON_as_Classes so that should be alright.
Generated classes:
namespace TvSeries
{
public class Show
{
public string title { get; set; }
public string imdb_id { get; set; }
public string epguide_name { get; set; }
}
public class __invalid_type__1
{
public Show show { get; set; }
public string title { get; set; }
public int number { get; set; }
public int season { get; set; }
public string release_date { get; set; }
}
public class Show2
{
public string title { get; set; }
public string imdb_id { get; set; }
public string epguide_name { get; set; }
}
public class __invalid_type__2
{
public Show2 show { get; set; }
public string title { get; set; }
public int number { get; set; }
public int season { get; set; }
public string release_date { get; set; }
}
public class Show3
{
public string title { get; set; }
public string imdb_id { get; set; }
public string epguide_name { get; set; }
}
public class __invalid_type__3
{
public Show3 show { get; set; }
public string title { get; set; }
public int number { get; set; }
public int season { get; set; }
public string release_date { get; set; }
}
public class Show4
{
public string title { get; set; }
public string imdb_id { get; set; }
public string epguide_name { get; set; }
}
public class __invalid_type__4
{
public Show4 show { get; set; }
public string title { get; set; }
public int number { get; set; }
public int season { get; set; }
public string release_date { get; set; }
}
public class Show5
{
public string title { get; set; }
public string imdb_id { get; set; }
public string epguide_name { get; set; }
}
public class __invalid_type__5
{
public Show5 show { get; set; }
public string title { get; set; }
public int number { get; set; }
public int season { get; set; }
public string release_date { get; set; }
}
public class Show6
{
public string title { get; set; }
public string imdb_id { get; set; }
public string epguide_name { get; set; }
}
public class __invalid_type__6
{
public Show6 show { get; set; }
public string title { get; set; }
public int number { get; set; }
public int season { get; set; }
public string release_date { get; set; }
}
public class Show7
{
public string title { get; set; }
public string imdb_id { get; set; }
public string epguide_name { get; set; }
}
public class __invalid_type__7
{
public Show7 show { get; set; }
public string title { get; set; }
public int number { get; set; }
public int season { get; set; }
public string release_date { get; set; }
}
public class RootObject
{
public List<__invalid_type__1> __invalid_name__1 { get; set; }
public List<__invalid_type__2> __invalid_name__2 { get; set; }
public List<__invalid_type__3> __invalid_name__3 { get; set; }
public List<__invalid_type__4> __invalid_name__4 { get; set; }
public List<__invalid_type__5> __invalid_name__5 { get; set; }
public List<__invalid_type__6> __invalid_name__6 { get; set; }
public List<__invalid_type__7> __invalid_name__7 { get; set; }
}
}
Here is simple main class to print it out to the console:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Script.Serialization;
using Newtonsoft.Json;
namespace TvSeries
{
class Program
{
static void Main(string[] args)
{
using (WebClient wc = new WebClient())
{
var json = wc.DownloadString("http://epguides.frecar.no/show/gameofthrones/");
//Console.WriteLine(json);
RootObject obj = JsonConvert.DeserializeObject<RootObject>(json);
foreach (var item in obj.__invalid_name__1)
{
Console.WriteLine("Show: {0}, release date: {1}", item.show.title, item.release_date);
}
Console.ReadKey();
}
}
}
}
So the actual question is why is not deserializing or working properly, because the objects are still null? I am missing something important? I have also tried JavaScriptSerializer() but it doesn't fix my problem.
You use an attribute like this:
[JsonProperty("show")]
public Show2 Show2 { get; set; }
As user3791372 said, you should tidy up the generated classes. However these classes where generated because the response looks like this
{ "1":[{...}...], "2":[{...}...],...}. So you first need to get rid of "1", "2" and define your own types for clean code. the result will look like this
class Show
{
public string title { get; set; }
public string imdb_id { get; set; }
public string epguide_name { get; set; }
}
class Episode
{
public Show show { get; set; }
public string title { get; set; }
public int number { get; set; }
public int season { get; set; }
public DateTime release_date { get; set; }
}
class Program
{
static void Main(string[] args)
{
using (WebClient wc = new WebClient())
{
//download json string
var json = wc.DownloadString("http://epguides.frecar.no/show/gameofthrones/");
//convert json to dynamic object
JObject obj = JObject.Parse(json);
//create an array that have as many elements as the children of obj => {"1", "2", "3", ...}
JArray[] results = new JArray[obj.Children().Count()];
//fill the array with the children of obj => results[6] = "[{"show": {"title": "Game of Thrones", "imdb_id": "tt0944947", "epguide_name": "gameofthrones"}, "title": "TBA", "number": 1, "season": 7, "release_date": "2017-06-25"}]"
for (int i = 0; i < results.Length; i++)
{
results[i] = (JArray)obj[(i + 1).ToString()];
}
//deserialize each item in results to List<Episode> if you checked the response it returns arrays of episodes
List<List<Episode>> seasons = new List<List<Episode>>(results.Length);
foreach (var item in results)
{
seasons.Add(JsonConvert.DeserializeObject<List<Episode>>(item.ToString()));
}
//output the result
foreach (var season in seasons)
{
foreach (var episod in season)
{
Console.WriteLine("Show: {0}, release date: {1}", episod.show.title, episod.release_date);
}
}
Console.ReadKey();
}
}
}

API returning a bunch of \t and \n

what am I doing wrong here? i'm trying to consume the ncaa data but I'm getting a bunch of \t and \n in my data, which makes it so I can't serialize it to an object. Here is my function, you can literally run this as it takes no credentials to get the data.
public string GetGameInfo(DateTime dt)
{
string content = string.Empty;
string url = "http://data.ncaa.com/jsonp/scoreboard/baseball/d1/2016/04/06/scoreboard.html";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "application/json";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream resStream = response.GetResponseStream();
using (StreamReader sr = new StreamReader(resStream))
{
content = sr.ReadToEnd();
}
return content;
}
/// <summary>
/// Summary description for Ncaa
/// </summary>
namespace Ncaa
{
public class callbackWrapper
{
public List<scoreboard> scoreboard { get; set; }
}
public class scoreboard
{
public DateTime day { get; set; }
public List<games> games { get; set; }
}
public class games
{
public string id { get; set; }
public string conference { get; set; }
public string gameState { get; set; }
public string startDate { get; set; }
public string startDateDisplay { get; set; }
public string startTime { get; set; }
public string startTimeEpoch { get; set; }
public string currentPeriod { get; set; }
public string finalMessage { get; set; }
public string gameStatus { get; set; }
public string periodStatus { get; set; }
public string downToGo { get; set; }
public string timeclock { get; set; }
public string network_logo { get; set; }
public string location { get; set; }
public string contestName { get; set; }
public string url { get; set; }
public string highlightsUrl { get; set; }
public string liveAudioUrl { get; set; }
public string gameCenterUrl { get; set; }
//public ChampInfo champInfo { get; set; }
//public IList<object> videos { get; set; }
public home home { get; set; }
public away away { get; set; }
}
public class home
{
public string teamRank { get; set; }
public IList<int> RHEBreakdown { get; set; }
public string iconURL { get; set; }
public string name { get; set; }
public string nameRaw { get; set; }
public string nameSeo { get; set; }
public string shortname { get; set; }
public string color { get; set; }
//public Social social { get; set; }
public string description { get; set; }
public string currentScore { get; set; }
public IList<string> scoreBreakdown { get; set; }
public string winner { get; set; }
}
public class away
{
public string teamRank { get; set; }
public IList<int> RHEBreakdown { get; set; }
public string iconURL { get; set; }
public string name { get; set; }
public string nameRaw { get; set; }
public string nameSeo { get; set; }
public string shortname { get; set; }
public string color { get; set; }
//public Social social { get; set; }
public string description { get; set; }
public string currentScore { get; set; }
public IList<string> scoreBreakdown { get; set; }
public string winner { get; set; }
}
}
protected void Page_Load(object sender, EventArgs e)
{
var json = GetGameInfo(DateTime.Now);
//this one doesn't work
//JsonConvert.DeserializeObject<Ncaa.callbackWrapper>(json);
//I tried removing the /ts and ns with no luck too
json = json.Replace("\t", string.Empty).Replace("\n", string.Empty);
JsonConvert.DeserializeObject<Ncaa.callbackWrapper>(json);
}
First of all, to answer why there's bunch of \ts and \ns in the response is because they ARE in your file. Those are respectively the tab character and the new line character.
I am not sure how you parse this , but most parsers should be able to handle this. In case you wrote your own, please post that code.
If the data returned will always be of format callback(JSON) you could strip the function call and simply parse the JSON using NewtonsoftJSON
EDIT: After reviewing the added code, I can notice that you are not stripping the function call. You should remove that and try again ( e.g. try removing everything until the first ocurrence of the { character and after last, or any other way you like )
Ok, so I did get it working. Doing this to the json helped.
json = json.Replace("callbackWrapper(", string.Empty).Replace(");", string.Empty);
Then, just parsing it as a scoreboard object, instead of a callback wrapper object.

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;

Categories