Im new in developing windows phone app --> i have problem so i have tried all the possible solutions but with no vain:-
the application tried to take result from webservice the result come back like this:-
{"d":"{\"sessionid\":null,\"VersionInfo\":{\"Rel\":0,\"Ver\":0,\"Patch\":0,\"ForceUpdate\":0,\"UpdateType\":0,\"Globals\":{\"MultiSessionsAllowed\":true,\"CommCalcType\":1,\"PriceChangedTimer\":20,\"ValidLotsLocation\":2,\"CustumizeTradeMsg\":true,\"FirstWhiteLabeledOffice\":null,\"DealerTreePriv\":0,\"ClientConnectTimer\":200,\"ClientTimeoutTimer\":500,\"DefaultLots\":0.01,\"WebSecurityID\":\"agagag\",\"ServerGMT\":3}},\"SystemLockInfo\":{\"MinutesRemaining\":0,\"HoursRemaining\":0,\"DaysRemaining\":0,\"Maintanance\":0,\"WillBeLocked\":1},\"FirstWhiteLabel\":\"HS Dev\",\"WLID\":\"3\",\"CheckWhiteLabel\":true,\"Password\":\"1234\",\"Username\":\"obeidat\",\"LastTickTime\":\"\/Date(1396613678728)\/\",\"SelectedAccount\":12345791,\"Name\":0,\"CompanyName\":\"HS Dev\",\"UserId\":579,\"DemoClient\":\"0\",\"FName\":\"obeidat\",\"SName\":null,\"TName\":null,\"LName\":null,\"Sms\":null,\"isReadOnly\":\"0\",\"SchSms\":\"0\",\"AlertSms\":\"0\",\"Temp\":null,\"GMTOffset\":\"5\",\"SvrGMT\":\"3\",\"ClientType\":null,\"EnableNews\":\"0\",\"PublicSlideNews\":\"\",\"PrivateSlideNews\":\"Thanks for using our platform##We will inform you here with any private news\",\"DealerTreePriv\":1}"}
so i have tried to parse it but it give me errors after that i have tried locally removed the {"d":" and \"LastTickTime\":\"\/Date(1396613678728)\/\" from the string with no connection to webservice and its working fine i use this code :-
// Constructor
public MainPage()
{
InitializeComponent();
// Sample code to localize the ApplicationBar
//BuildLocalizedApplicationBar();
}
//Json classes
public class OuterRootObject
{
public string d { get; set; }
}
public class Globals
{
public bool MultiSessionsAllowed { get; set; }
public int CommCalcType { get; set; }
public int PriceChangedTimer { get; set; }
public int ValidLotsLocation { get; set; }
public bool CustumizeTradeMsg { get; set; }
public object FirstWhiteLabeledOffice { get; set; }
public int DealerTreePriv { get; set; }
public int ClientConnectTimer { get; set; }
public int ClientTimeoutTimer { get; set; }
public double DefaultLots { get; set; }
public string WebSecurityID { get; set; }
public int ServerGMT { get; set; }
}
public class VersionInfo
{
public int Rel { get; set; }
public int Ver { get; set; }
public int Patch { get; set; }
public int ForceUpdate { get; set; }
public int UpdateType { get; set; }
public Globals Globals { get; set; }
}
public class SystemLockInfo
{
public int MinutesRemaining { get; set; }
public int HoursRemaining { get; set; }
public int DaysRemaining { get; set; }
public int Maintanance { get; set; }
public int WillBeLocked { get; set; }
}
public class RootObject
{
public string sessionid { get; set; }
public VersionInfo VersionInfo { get; set; }
public SystemLockInfo SystemLockInfo { get; set; }
public string FirstWhiteLabel { get; set; }
public string WLID { get; set; }
public bool CheckWhiteLabel { get; set; }
public string Password { get; set; }
public string Username { get; set; }
public DateTime LastTickTime { get; set; }
public int SelectedAccount { get; set; }
public int Name { get; set; }
public object ServicePath { get; set; }
public string GWSessionID { get; set; }
public string IP { get; set; }
public string SessionDateStart { get; set; }
public string CompanyName { get; set; }
public string UserId { get; set; }
public string DemoClient { get; set; }
public string FName { get; set; }
public string SName { get; set; }
public string TName { get; set; }
public string LName { get; set; }
public object Sms { get; set; }
public string isReadOnly { get; set; }
public string SchSms { get; set; }
public string AlertSms { get; set; }
public object Temp { get; set; }
public string GMTOffset { get; set; }
public string SvrGMT { get; set; }
public object ClientType { get; set; }
public string EnableNews { get; set; }
public string PublicSlideNews { get; set; }
public string PrivateSlideNews { get; set; }
public int DealerTreePriv { get; set; }
}
private void Button_Click(object sender, RoutedEventArgs e)
{
var jsonString =
"{\"sessionid\":null,\"VersionInfo\":{\"Rel\":0,\"Ver\":0,\"Patch\":0,\"ForceUpdate\":0,\"UpdateType\":0,\"Globals\":{\"MultiSessionsAllowed\":true,\"CommCalcType\":1,\"PriceChangedTimer\":20,\"ValidLotsLocation\":2,\"CustumizeTradeMsg\":true,\"FirstWhiteLabeledOffice\":null,\"DealerTreePriv\":0,\"ClientConnectTimer\":200,\"ClientTimeoutTimer\":500,\"DefaultLots\":0.01,\"WebSecurityID\":\"agagag\",\"ServerGMT\":3}},\"SystemLockInfo\":{\"MinutesRemaining\":0,\"HoursRemaining\":0,\"DaysRemaining\":0,\"Maintanance\":0,\"WillBeLocked\":1},\"FirstWhiteLabel\":\"HS Dev\",\"WLID\":\"3\",\"CheckWhiteLabel\":true,\"Password\":\"1234\",\"Username\":\"obeidat\",\"SelectedAccount\":12345791,\"Name\":0,\"CompanyName\":\"HS Dev\",\"UserId\":-579,\"DemoClient\":\"0\",\"FName\":\"obeidat\",\"SName\":null,\"TName\":null,\"LName\":null,\"Sms\":null,\"isReadOnly\":\"0\",\"SchSms\":\"0\",\"AlertSms\":\"0\",\"Temp\":null,\"GMTOffset\":\"5\",\"SvrGMT\":\"3\",\"ClientType\":null,\"EnableNews\":\"0\",\"PublicSlideNews\":\"\",\"PrivateSlideNews\":\"Thanks for using our platform##We will inform you here with any private news\",\"DealerTreePriv\":1}";
RootObject jsonObject = JsonConvert.DeserializeObject<RootObject>(jsonString);
MessageBox.Show("hello " + jsonObject.Username + "" + jsonObject.UserId);
int val1 = Convert.ToInt16(jsonObject.UserId);
if (val1 > 0)
MessageBox.Show("You are logedin");
else
{
MessageBox.Show("Sorry Please login");
}
}
// // Create a new button and set the text value to the localized string from AppResources.
// ApplicationBarIconButton appBarButton = new ApplicationBarIconButton(new Uri("/Assets/AppBar/appbar.add.rest.png", UriKind.Relative));
// appBarButton.Text = AppResources.AppBarButtonText;
// ApplicationBar.Buttons.Add(appBarButton);
// // Create a new menu item with the localized string from AppResources.
// ApplicationBarMenuItem appBarMenuItem = new ApplicationBarMenuItem(AppResources.AppBarMenuItemText);
// ApplicationBar.MenuItems.Add(appBarMenuItem);
//}
}
}
Please help me to parse all of the json result (locally i mean without conection to web)and what is the code to do that.
thank you all
First, your JSON is all a string property of "D". You can't deserialize it to RootClass. Second, your JSON contains invalid escape characters in the LastTickTime area. I removed both of these, and the JSON parses without errors of any kind. I just used a console app to test it.
var s = "{\"sessionid\":null,\"VersionInfo\":{\"Rel\":0,\"Ver\":0,\"Patch\":0,\"ForceUpdate\":0,\"UpdateType\":0,\"Globals\":{\"MultiSessionsAllowed\":true,\"CommCalcType\":1,\"PriceChangedTimer\":20,\"ValidLotsLocation\":2,\"CustumizeTradeMsg\":true,\"FirstWhiteLabeledOffice\":null,\"DealerTreePriv\":0,\"ClientConnectTimer\":200,\"ClientTimeoutTimer\":500,\"DefaultLots\":0.01,\"WebSecurityID\":\"agagag\",\"ServerGMT\":3}},\"SystemLockInfo\":{\"MinutesRemaining\":0,\"HoursRemaining\":0,\"DaysRemaining\":0,\"Maintanance\":0,\"WillBeLocked\":1},\"FirstWhiteLabel\":\"HS Dev\",\"WLID\":\"3\",\"CheckWhiteLabel\":true,\"Password\":\"1234\",\"Username\":\"obeidat\",\"SelectedAccount\":12345791,\"Name\":0,\"CompanyName\":\"HS Dev\",\"UserId\":579,\"DemoClient\":\"0\",\"FName\":\"obeidat\",\"SName\":null,\"TName\":null,\"LName\":null,\"Sms\":null,\"isReadOnly\":\"0\",\"SchSms\":\"0\",\"AlertSms\":\"0\",\"Temp\":null,\"GMTOffset\":\"5\",\"SvrGMT\":\"3\",\"ClientType\":null,\"EnableNews\":\"0\",\"PublicSlideNews\":\"\",\"PrivateSlideNews\":\"Thanks for using our platform##We will inform you here with any private news\",\"DealerTreePriv\":1}";
var foo = JsonConvert.DeserializeObject<RootObject>(s);
Console.WriteLine(foo.UserId); // Writes 579
UPDATE
If you have no control over what you get back, do the following:
Take the response and get rid of the / combination. As such:
string webResponse = "your long web response from the server";
webResponse = webResponse.Replace(#"\/", "/");
// If dynamic isn't in the phone subset, you'll need a class here containing "d" as a string.
var jsonOuter = JsonConvert.DeserializeObject<dynamic>(webResponse);
var jsonInner = JsonConvert.DeserializeObject<RootObject>(jsonOuter.d);
if (jsonInner.UserId > .....)
Related
I'm trying to consume a web API into Blazor but am struggling to extract certain information from the API
using System.Text.Json;
namespace CA3.Song
{
public class SongService : ISongService
{
private readonly HttpClient _httpClient;
const string _baseUrl = "https://genius-song-lyrics1.p.rapidapi.com/";
const string _songEndpoint = "songs/chart?time_period=day&chart_genre=all&per_page=10&page=1";
const string _host = "genius-song-lyrics1.p.rapidapi.com";
const string _key = "{key}";
public SongService(HttpClient httpClient)
{
_httpClient = httpClient;
}
public async Task<List<SongItem>> GetSong()
{
Configure();
var response = await _httpClient.GetAsync(_songEndpoint);
var response_outcome = response.EnsureSuccessStatusCode;
using var stream = await response.Content.ReadAsStreamAsync();
var dto = await JsonSerializer.DeserializeAsync<SongDto>(stream);
return dto.response.chart_items.Select(n => new SongItem { Artist = n.item.primary_artist, Title = n.item.primary_title, ReleaseDate = n.primary_release_date }).ToList().T ;
}
private void Configure()
{
_httpClient.BaseAddress = new Uri(_baseUrl);
_httpClient.DefaultRequestHeaders.Add("X-RapidAPI-Host", _host);
_httpClient.DefaultRequestHeaders.Add("X-Rapid-Key", _key);
}
}
}
The issue is on the return statement using LINQ.
namespace CA3.Song
{
public class SongDto
{
public Meta meta { get; set; }
public Response response { get; set; }
}
public class Meta
{
public int status { get; set; }
}
public class Response
{
public Chart_Items[] chart_items { get; set; }
public int next_page { get; set; }
}
public class Chart_Items
{
public string _type { get; set; }
public string type { get; set; }
public Item item { get; set; }
}
public class Item
{
public string _type { get; set; }
public int annotation_count { get; set; }
public string api_path { get; set; }
public string artist_names { get; set; }
public string full_title { get; set; }
public string header_image_thumbnail_url { get; set; }
public string header_image_url { get; set; }
public int id { get; set; }
public bool instrumental { get; set; }
public int lyrics_owner_id { get; set; }
public string lyrics_state { get; set; }
public int lyrics_updated_at { get; set; }
public string path { get; set; }
public int pyongs_count { get; set; }
public string relationships_index_url { get; set; }
public Release_Date_Components release_date_components { get; set; }
public string release_date_for_display { get; set; }
public string song_art_image_thumbnail_url { get; set; }
public string song_art_image_url { get; set; }
public Stats stats { get; set; }
public string title { get; set; }
public string title_with_featured { get; set; }
public int updated_by_human_at { get; set; }
public string url { get; set; }
public Featured_Artists[] featured_artists { get; set; }
public Primary_Artist primary_artist { get; set; }
}
public class Release_Date_Components
{
public int year { get; set; }
public int month { get; set; }
public int day { get; set; }
}
public class Stats
{
public int unreviewed_annotations { get; set; }
public int concurrents { get; set; }
public bool hot { get; set; }
public int pageviews { get; set; }
}
public class Primary_Artist
{
public string _type { get; set; }
public string api_path { get; set; }
public string header_image_url { get; set; }
public int id { get; set; }
public string image_url { get; set; }
public string index_character { get; set; }
public bool is_meme_verified { get; set; }
public bool is_verified { get; set; }
public string name { get; set; }
public string slug { get; set; }
public string url { get; set; }
public int iq { get; set; }
}
public class Featured_Artists
{
public string _type { get; set; }
public string api_path { get; set; }
public string header_image_url { get; set; }
public int id { get; set; }
public string image_url { get; set; }
public string index_character { get; set; }
public bool is_meme_verified { get; set; }
public bool is_verified { get; set; }
public string name { get; set; }
public string slug { get; set; }
public string url { get; set; }
public int iq { get; set; }
}
}
Above is the JSON file and I'm trying to extract the artist name, song title and release date from Item but it isn't in a list so I'm trying to find a way to extract this info using LINQ. Any help would be greatly appreciated !
I think you misinterpreted the declaration of the JSON. They are stored in an array Chart_Items[] chart_items thus you may use linq.
There are many ways to do this, I took advantage of named tuples in modern C# paired with linq.
Response r = new Response();//some resonse from api
var results = r.chart_items.Select(i => (i.item.artist_names, i.item.title, i.item.release_date_components)).ToList();
foreach(var result in results)
{
string artist_names = result.artist_names;
string title = result.title;
Release_Date_Components release_date_components = result.release_date_components;
}
I have some problems parsing huge xml in c#, mostly because I returned from apex to c# after a long time. So far I cant get working even this
private void read_Click(object sender, EventArgs e)
{
XElement xmlDoc = XElement.Load(#"D:\\AOI\\Samples\\Error\\60A84130868D_20180428035150_AOI-mek1.xml");
var loaded_File =
from fileInfo in xmlDoc.Descendants("result_file")
select new File
{
filename = fileInfo.Element("designator").Value,
supplier = fileInfo.Element("supplier").Value,
date_created = fileInfo.Element("date").Value,
station_ID = fileInfo.Element("station_ID").Value,
operator_ID = fileInfo.Element("operator_ID").Value,
program = fileInfo.Element("program").Value,
side_variant = fileInfo.Element("side_variant").Value
};
foreach(var item in loaded_File) {
System.Diagnostics.Debug.WriteLine(item.ToString());
}
}
Xml file looks as follows with multiple good_no and error_no, can someone navigate me how to load the file properly? I need it afterwards to insert it into database, but that should be just fine.
<result_file>
<filename>60Axxxxxek1</filename>
<supplier>Maxxxxz</supplier>
<date>20xxxx5150</date>
<station_ID>Axxxx1</station_ID>
<operator_ID></operator_ID>
<program>Xxxx01</program>
<side_variant>A</side_variant>
<pcbs_in_panel>0</pcbs_in_panel>
<serial>60xxxxxx8D</serial>
<status>GOOD</status>
<starttime>20180xxxxxx150</starttime>
<lot_no></lot_no>
<info>
<window_no>354</window_no>
<packs_no>343</packs_no>
<error_total>1</error_total>
<error_conf>0</error_conf>
<inspection_time>5</inspection_time>
<panel_image>AOxxxxx_A.jpg</panel_image>
<panel_image_location>x:\xml</panel_image_location>
<ng_image_location>x:\xml\Xxxxx0428</ng_image_location>
<repaired>0</repaired>
</info>
<errors>
<error_no name="1">
<designator></designator>
<pin></pin>
<stamp_name>Bridge:Short</stamp_name>
<package_name></package_name>
<errortype>-</errortype>
<error_contents></error_contents>
<pcb_no></pcb_no>
<feeder_no></feeder_no>
<pos_x>8760</pos_x>
<pos_y>4600</pos_y>
<window>-313</window>
<ng_message></ng_message>
<comment>(* *){Bridge:Short}</comment>
<ng_image>Xxxxxx13.jpg</ng_image>
</error_no>
</errors>
<goods>
<good_no name="1">
<designator>Ixxx1</designator>
<pin>Ixxx1</pin>
<stamp_name>Ixxxxrat</stamp_name>
<package_name>Ixxxx1</package_name>
<pcb_no></pcb_no>
<feeder_no></feeder_no>
<pos_x>3082</pos_x>
<pos_y>3202</pos_y>
<window>+1</window>
<comment>(* *){Ixxxxat}</comment>
</good_no>
</goods>
</result_file>
Thanks for advices.
EDIT:
I have also prepared classes for that
public class File
{
public string name { get; set; }
public string filename { get; set; }
public string supplier { get; set; }
public string date_created { get; set; }
public string station_ID { get; set; }
public string operator_ID { get; set; }
public string program { get; set; }
public string side_variant { get; set; }
public string pcbs_in_panel { get; set; }
public string serial { get; set; }
public string status { get; set; }
public string starttime { get; set; }
public string lot_no { get; set; }
public string window_no { get; set; }
public string packs_no { get; set; }
public string error_total { get; set; }
public string error_conf { get; set; }
public string inspection_time { get; set; }
public string panel_image { get; set; }
public string panel_image_location { get; set; }
public string ng_image_location { get; set; }
public string repaired { get; set; }
public List<Good> Goods = new List<Good>();
public List<Error> Errors = new List<Error>();
}
public class Good
{
public List<Good_no> Good_ones = new List<Good_no>();
}
public class Error
{
public List<Error_no> Error_ones = new List<Error_no>();
}
public class Good_no
{
public string name { get; set; }
public string designator { get; set; }
public string pin { get; set; }
public string stamp_name { get; set; }
public string package_name { get; set; }
public string pcb_no { get; set; }
public string feeder_no { get; set; }
public string pos_x { get; set; }
public string pos_y { get; set; }
public string window { get; set; }
public string comment { get; set; }
}
public class Error_no
{
public string name { get; set; }
public string designator { get; set; }
public string pin { get; set; }
public string stamp_name { get; set; }
public string package_name { get; set; }
public string errortype { get; set; }
public string error_contents { get; set; }
public string pcb_no { get; set; }
public string feeder_no { get; set; }
public string pos_x { get; set; }
public string pos_y { get; set; }
public string window { get; set; }
public string ng_message { get; set; }
public string comment { get; set; }
public string ng_image { get; set; }
}
You should simplify the class structure:
public class File
{
public string Filename { get; set; }
public string Supplier { get; set; }
// ...
public List<Good> Goods { get; set; }
public List<Error> Errors { get; set; }
}
public class Good
{
public string Name { get; set; }
public string Designator { get; set; }
public string Pin { get; set; }
// ...
}
public class Error
{
public string Name { get; set; }
public string Designator { get; set; }
// ...
}
Then the reading would look like this:
var xmlDoc = XElement.Load("test.xml");
var loadedFile = new File
{
Filename = xmlDoc.Element("filename").Value,
Supplier = xmlDoc.Element("supplier").Value,
// ...
Goods = (from good in xmlDoc.Element("goods").Elements("good_no")
select new Good
{
Name = good.Attribute("name").Value,
Designator = good.Element("designator").Value,
Pin = good.Element("pin").Value
// ...
})
.ToList()
};
If you want to read the XML-File, I recommmend you to deserialize the XML-files.
For this, your class-definition isn't complete. In Visual Studio is a tool, called xsd.exe. With this tool you can transform your XML-File first in a XSD-Schema. From the XSD-Schema you can generate the required classes.
To transform to XSD-Schema: xsd.exe {Filename.xml}
To transform to C#-Classes: xsd.exe /c {Filename.xsd}
XSD have many more options (see: https://msdn.microsoft.com/de-de/library/x6c1kb0s(v=vs.120).aspx)
If you have the correct classes you can read the XML-File with the XMLSerializer (see: https://msdn.microsoft.com/de-de/library/tz8csy73(v=vs.110).aspx)
been a while since I posted here. I'm working on an app and need to fetch statistics for a particular video using JSON (C#, UWP).
I already have the statistics as a JSON string but can't seem to parse them properly using Newtonsoft. The value always comes back null. This is my code:
var url = "https://www.googleapis.com/youtube/v3/videos?id=" + videoId + "&key=" + cl.googleAPIKey + "&part=snippet,contentDetails,statistics,status";
var http = new HttpClient();
var response = await http.GetStringAsync(url);
var statistics = JsonConvert.DeserializeObject<Statistics>(response);
string totalViews = statistics.viewCount;
The classes generated by Json2CSharp are:
public class PageInfo
{
public int totalResults { get; set; }
public int resultsPerPage { get; set; }
}
public class Default
{
public string url { get; set; }
public int width { get; set; }
public int height { get; set; }
}
public class Medium
{
public string url { get; set; }
public int width { get; set; }
public int height { get; set; }
}
public class High
{
public string url { get; set; }
public int width { get; set; }
public int height { get; set; }
}
public class Standard
{
public string url { get; set; }
public int width { get; set; }
public int height { get; set; }
}
public class Maxres
{
public string url { get; set; }
public int width { get; set; }
public int height { get; set; }
}
public class Thumbnails
{
public Default #default { get; set; }
public Medium medium { get; set; }
public High high { get; set; }
public Standard standard { get; set; }
public Maxres maxres { get; set; }
}
public class Localized
{
public string title { get; set; }
public string description { get; set; }
}
public class Snippet
{
public DateTime publishedAt { get; set; }
public string channelId { get; set; }
public string title { get; set; }
public string description { get; set; }
public Thumbnails thumbnails { get; set; }
public string channelTitle { get; set; }
public List<string> tags { get; set; }
public string categoryId { get; set; }
public string liveBroadcastContent { get; set; }
public Localized localized { get; set; }
}
public class ContentDetails
{
public string duration { get; set; }
public string dimension { get; set; }
public string definition { get; set; }
public string caption { get; set; }
public bool licensedContent { get; set; }
public string projection { get; set; }
}
public class Status
{
public string uploadStatus { get; set; }
public string privacyStatus { get; set; }
public string license { get; set; }
public bool embeddable { get; set; }
public bool publicStatsViewable { get; set; }
}
public class Statistics
{
public string viewCount { get; set; }
public string likeCount { get; set; }
public string dislikeCount { get; set; }
public string favoriteCount { get; set; }
public string commentCount { get; set; }
}
public class Item
{
public string kind { get; set; }
public string etag { get; set; }
public string id { get; set; }
public Snippet snippet { get; set; }
public ContentDetails contentDetails { get; set; }
public Status status { get; set; }
public Statistics statistics { get; set; }
}
public class RootObject
{
public string kind { get; set; }
public string etag { get; set; }
public PageInfo pageInfo { get; set; }
public List<Item> items { get; set; }
}
As I say the value will always come back as null regardless of the video ID.
Does anyone have any ideas?
Thanks
You are deserializing to the wrong class. Json2Csharp generated many classes, but Statistics is way down the tree. You should deserialize the RootObject instead:
var root = JsonConvert.DeserializeObject<RootObject>( response );
And then navigate to the statistics within the resulting class structure like for example:
foreach ( var statistics in root.Items.Select( i => i.Statistics) )
{
//do something
}
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.
I'm trying to make an application that can show local TV guide trough JSON rest api C #, but has some problems with deserialization of my Json response.
i'm only intresest in the array NOW in my json call and i do not own the api service.
I get this error message:
An exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.DLL but was not handled in user code
Additional information: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[TDC_Play_TV_Mobil.superclass2+Now]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Path 'now', line 1, position 7.
My function:
private HttpClient client;
public async Task<List<superclass2.Now>> GetComments()
{
client = new HttpClient();
var response = await client.GetAsync(new Uri("http://api.yousee.tv/rest/tvguide/nowandnext/"));
if (response.IsSuccessStatusCode)
{
string json = await response.Content.ReadAsStringAsync();
System.Diagnostics.Debug.WriteLine(json);
var task = Task.Factory.StartNew(() => JsonConvert.DeserializeObject<List<superclass2.Now>>(json));
var value = await task;
// List<superclass2.Now> comments = Newtonsoft.Json.JsonConvert.DeserializeObject<List<superclass2.Now>>(await json);
System.Diagnostics.Debug.WriteLine("Comments er lavet");
return value;
}
else
{
throw new Exception("Errorhandling message");
}
}
My class file:
public class superclass2
{
public class Logos
{
public string small { get; set; }
public string large { get; set; }
public string small_seapp { get; set; }
public string large_seapp { get; set; }
public string extralarge { get; set; }
public string super { get; set; }
public string mega { get; set; }
public string netgem { get; set; }
public string svg { get; set; }
}
public class ChannelInfo
{
public string name { get; set; }
public string shortname { get; set; }
public string logo_image_prefix { get; set; }
public Logos logos { get; set; }
public int archivedays { get; set; }
public string channelcolor { get; set; }
}
public class FormattedDate
{
public string time_begin { get; set; }
public string time_end { get; set; }
public string date { get; set; }
}
public class ImagesSixteenbynine
{
public string large { get; set; }
public string medium { get; set; }
public string small { get; set; }
}
public class ImagesFourbythree
{
public string large { get; set; }
public string small { get; set; }
}
public class ImagesSquare
{
public string large { get; set; }
public string medium { get; set; }
public string small { get; set; }
}
public class Now
{
public int id { get; set; }
public int dvb_id { get; set; }
public int channel { get; set; }
public ChannelInfo channel_info { get; set; }
public string orgtitle { get; set; }
public string cast { get; set; }
public string directors { get; set; }
public string series_info { get; set; }
public int series_id { get; set; }
public string series_name { get; set; }
public bool allowseriesrecording { get; set; }
public int totalinarchive { get; set; }
public int popularity_score { get; set; }
public int totalupcoming { get; set; }
public int category { get; set; }
public int subcategory { get; set; }
public string category_string { get; set; }
public string subcategory_string { get; set; }
public int begin { get; set; }
public object actual_begin { get; set; }
public int end { get; set; }
public int actual_end { get; set; }
public int tvdate { get; set; }
public FormattedDate formatted_date { get; set; }
public string title { get; set; }
public string description { get; set; }
public bool archive { get; set; }
public bool scrubbingallowed { get; set; }
public int expiresfromarchive { get; set; }
public bool startover { get; set; }
public string imageprefix { get; set; }
public ImagesSixteenbynine images_sixteenbynine { get; set; }
public ImagesFourbythree images_fourbythree { get; set; }
public ImagesSquare images_square { get; set; }
public List<object> decorations { get; set; }
}
public class Logos2
{
public string small { get; set; }
public string large { get; set; }
public string small_seapp { get; set; }
public string large_seapp { get; set; }
public string extralarge { get; set; }
public string super { get; set; }
public string mega { get; set; }
public string netgem { get; set; }
public string svg { get; set; }
}
public class ChannelInfo2
{
public string name { get; set; }
public string shortname { get; set; }
public string logo_image_prefix { get; set; }
public Logos2 logos { get; set; }
public int archivedays { get; set; }
public string channelcolor { get; set; }
}
public class FormattedDate2
{
public string time_begin { get; set; }
public string time_end { get; set; }
public string date { get; set; }
}
public class ImagesSixteenbynine2
{
public string large { get; set; }
public string medium { get; set; }
public string small { get; set; }
}
public class ImagesFourbythree2
{
public string large { get; set; }
public string small { get; set; }
}
public class ImagesSquare2
{
public string large { get; set; }
public string medium { get; set; }
public string small { get; set; }
}
public class Next
{
public int id { get; set; }
public int dvb_id { get; set; }
public int channel { get; set; }
public ChannelInfo2 channel_info { get; set; }
public string orgtitle { get; set; }
public string cast { get; set; }
public string directors { get; set; }
public string series_info { get; set; }
public int series_id { get; set; }
public string series_name { get; set; }
public bool allowseriesrecording { get; set; }
public int totalinarchive { get; set; }
public int popularity_score { get; set; }
public int totalupcoming { get; set; }
public int category { get; set; }
public int subcategory { get; set; }
public string category_string { get; set; }
public string subcategory_string { get; set; }
public int begin { get; set; }
public int actual_begin { get; set; }
public int end { get; set; }
public int actual_end { get; set; }
public int tvdate { get; set; }
public FormattedDate2 formatted_date { get; set; }
public string title { get; set; }
public string description { get; set; }
public bool archive { get; set; }
public bool scrubbingallowed { get; set; }
public int expiresfromarchive { get; set; }
public bool startover { get; set; }
public string imageprefix { get; set; }
public ImagesSixteenbynine2 images_sixteenbynine { get; set; }
public ImagesFourbythree2 images_fourbythree { get; set; }
public ImagesSquare2 images_square { get; set; }
public List<object> decorations { get; set; }
}
public class RootObject
{
public List<Now> now { get; set; }
public List<Next> next { get; set; }
}
}
Your JSON isn't a List<superclass2.Now>, it's a superclass2.RootObject. So you need to do something like:
public async Task<List<superclass2.Now>> GetComments()
{
client = new HttpClient();
var response = await client.GetAsync(new Uri("http://api.yousee.tv/rest/tvguide/nowandnext/"));
if (response.IsSuccessStatusCode)
{
string json = await response.Content.ReadAsStringAsync();
System.Diagnostics.Debug.WriteLine(json);
var task = Task.Factory.StartNew(() => JsonConvert.DeserializeObject<superclass2.RootObject>(json));
var value = await task;
System.Diagnostics.Debug.WriteLine("Comments er lavet");
return (value == null ? null : value.now);
}
else
{
throw new Exception("Errorhandling message");
}
}
Agree with Jon Skeet it would be nicer to eliminate the nesting of classes, purely for improved readability. If you need these classes to exist only in a specific scope, it is better to use nested namespaces. They aren't causing your bug, however.