Cannot Serialize JSON - c#

I am trying to access data from a json at this url : http://na.lolesports.com/api/gameStatsFantasy.json?tournamentId=104.
I used a website called http://json2csharp.com/ to help create classes to serialize. It worked but I noticed the JSON had many duplicate instances of the same gameID, playerID and teamID(e.g one named Game2998 and Game29982 or team4 and team42).
public class RootObject
{
public TeamStats teamStats { get; set; }
public PlayerStats playerStats { get; set; }
}
public class TeamStats
{
public Dictionary<string, Game> GameID { get; set; }
}
public class PlayerStats
{
public Dictionary<string,game> gameID { get; set; }
}
public class Game
{
public string dateTime { get; set; }
public Team blueTeam { get; set; }
public Team purpleTeam { get; set; }
public string matchId { get; set; }
}
public class game
{
public string dateTime { get; set; }
public string matchId { get; set; }
public Player bluePlayer1 { get; set; }
public Player bluePlayer2 { get; set; }
public Player bluePlayer3 { get; set; }
public Player bluePlayer4 { get; set; }
public Player bluePlayer5 { get; set; }
public Player purplePlayer1 { get; set; }
public Player purplePlayer2 { get; set; }
public Player purplePlayer3 { get; set; }
public Player purplePlayer4 { get; set; }
public Player purplePlayer5 { get; set; }
}
public class Player
{
public int playerId { get; set; }
public int kills { get; set; }
public int deaths { get; set; }
public int assists { get; set; }
public int minionKills { get; set; }
public int doubleKills { get; set; }
public int tripleKills { get; set; }
public int quadraKills { get; set; }
public int pentaKills { get; set; }
public string playerName { get; set; }
public string role { get; set; }
}
public class Team
{
public int teamId { get; set; }
public string teamName { get; set; }
public int matchVictory { get; set; }
public int matchDefeat { get; set; }
public int baronsKilled { get; set; }
public int dragonsKilled { get; set; }
public int firstBlood { get; set; }
public int firstTower { get; set; }
public int firstInhibitor { get; set; }
public int towersKilled { get; set; }
}

Related

Deserialize JSON using NewtonSoft

I have created classes needed by help of a website, but can't deserialize.
public class Brand
{
public string name { get; set; }
}
public class Link
{
public string href { get; set; }
}
public class Price
{
public double current { get; set; }
}
public class RootObject
{
public Brand brand { get; set; }
public string href { get; set; }
public List<Link> links { get; set; }
public List<string> mpns { get; set; }
public string name { get; set; }
public Price price { get; set; }
public string productId { get; set; }
}
How I am trying in C#
string API = "https://www.verkkokauppa.com/resp-api/product?pids=552952"
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(API);
request.Method = "GET";
string result = "";
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
result = reader.ReadToEnd();
reader.Close();
dataStream.Close();
}
var jsonresult = JsonConvert.DeserializeObject<RootObject>(result);
foreach (Brand p in jsonresult)
{
Debug.WriteLine(p);
}
I know I'm doing something wrong, but can anyone help me to correctly get the elements from the classes above only?
There are few mistakes in the code you've provided:
The json which is received from endpoint, is a json array.
So, instead of deserialzing as RootObject you should deserialize as List<RootObject>.
While iterating through jsonresult you should use RootObject instead of Brand
So here is the complete solution:
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.Net;
using System.IO;
using System.Diagnostics;
public class Brand
{
public string name { get; set; }
}
public class Link
{
public string href { get; set; }
}
public class Price
{
public double current { get; set; }
}
public class RootObject
{
public Brand brand { get; set; }
public string href { get; set; }
public List<Link> links { get; set; }
public List<string> mpns { get; set; }
public string name { get; set; }
public Price price { get; set; }
public string productId { get; set; }
}
public class Program
{
public static void Main()
{
string API = "https://www.verkkokauppa.com/resp-api/product?pids=552952";
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(API);
request.Method = "GET";
string result = "";
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
result = reader.ReadToEnd();
reader.Close();
dataStream.Close();
}
var jsonresult = JsonConvert.DeserializeObject<List<RootObject>>(result);
foreach (RootObject p in jsonresult)
{
Debug.WriteLine(p.brand.name);
foreach (Link link in p.links){
Debug.WriteLine(link.href);
}
foreach (string mpn in p.mpns){
Debug.WriteLine(mpn);
}
}
}
}
And here is the online version just in case it's needed.
Finally, I did it.kindly change your Model. The model should match your JSON data. You can check the complete solution
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
namespace Jsondemo
{
public class Brand
{
public int id { get; set; }
public string name { get; set; }
public string slug { get; set; }
public string support { get; set; }
public string url { get; set; }
}
public class Path
{
public string id { get; set; }
public string name { get; set; }
}
public class Category
{
public string id { get; set; }
public string name { get; set; }
public string slug { get; set; }
public List<Path> path { get; set; }
}
public class Installment
{
public int months { get; set; }
public int monthlySum { get; set; }
public double totalAmount { get; set; }
public double annualInterestRate { get; set; }
public double interest { get; set; }
public double fee { get; set; }
}
public class UiLabels
{
public string text { get; set; }
public string price { get; set; }
public string time { get; set; }
public List<string> tooltip { get; set; }
}
public class Installment2
{
public int months { get; set; }
public string monthlySum { get; set; }
public double totalAmount { get; set; }
public double annualInterestRate { get; set; }
public double interest { get; set; }
public double fee { get; set; }
}
public class UiLabels2
{
public string text { get; set; }
public string price { get; set; }
public string time { get; set; }
public List<string> tooltip { get; set; }
}
public class CompanyFinancing
{
public List<Installment2> installments { get; set; }
public UiLabels2 uiLabels { get; set; }
}
public class Financing
{
public List<Installment> installments { get; set; }
public string type { get; set; }
public double price { get; set; }
public UiLabels uiLabels { get; set; }
public CompanyFinancing companyFinancing { get; set; }
}
public class Image
{
public string __invalid_name__45 { get; set; }
public string __invalid_name__90 { get; set; }
public string __invalid_name__300 { get; set; }
public string __invalid_name__500 { get; set; }
public string __invalid_name__960 { get; set; }
public string orig { get; set; }
}
public class Link
{
public string name { get; set; }
public string type { get; set; }
public string href { get; set; }
}
public class Package
{
public int width { get; set; }
public int height { get; set; }
public int depth { get; set; }
public int volume { get; set; }
public int weight { get; set; }
}
public class Price
{
public double current { get; set; }
public double currentTaxless { get; set; }
public string currentFormatted { get; set; }
public double original { get; set; }
public double originalTaxless { get; set; }
public string originalFormatted { get; set; }
public object discountAmount { get; set; }
public object discountPercentage { get; set; }
public int taxRate { get; set; }
public object discount { get; set; }
public object deposit { get; set; }
public object unit { get; set; }
}
public class Rating
{
public int reviewCount { get; set; }
public int averageOverallRating { get; set; }
public int recommendedCount { get; set; }
}
public class Relations
{
public List<object> recommended { get; set; }
public List<object> newer { get; set; }
public List<object> older { get; set; }
public List<object> bundles { get; set; }
}
public class Restrictions
{
public bool isRestricted { get; set; }
public List<object> pickupAllowed { get; set; }
public List<object> postalCodeAllowed { get; set; }
public string description { get; set; }
public string descriptionShort { get; set; }
}
public class ShipmentPrice
{
public int id { get; set; }
public string name { get; set; }
public double price { get; set; }
public bool pickup { get; set; }
}
public class Js
{
public int stock { get; set; }
public string stockStatus { get; set; }
}
public class Pak
{
public int stock { get; set; }
public string stockStatus { get; set; }
}
public class Vendor
{
public int stock { get; set; }
public string stockStatus { get; set; }
}
public class Warehouses
{
public Js js { get; set; }
public Pak pak { get; set; }
public Vendor vendor { get; set; }
}
public class Web
{
public bool isAvailable { get; set; }
public bool isPurchasable { get; set; }
public int stock { get; set; }
public string stockStatus { get; set; }
public int minDays { get; set; }
public int maxDays { get; set; }
public Warehouses warehouses { get; set; }
public string ranking { get; set; }
}
public class Js2
{
public bool isAvailable { get; set; }
public bool isPurchasable { get; set; }
public int stock { get; set; }
public string stockStatus { get; set; }
public int minDays { get; set; }
public int maxDays { get; set; }
}
public class JsKioski
{
public bool isAvailable { get; set; }
public bool isPurchasable { get; set; }
public int stock { get; set; }
public string stockStatus { get; set; }
public int minDays { get; set; }
public int maxDays { get; set; }
}
public class Oul
{
public bool isAvailable { get; set; }
public bool isPurchasable { get; set; }
public int stock { get; set; }
public string stockStatus { get; set; }
public int minDays { get; set; }
public int maxDays { get; set; }
}
public class Pir
{
public bool isAvailable { get; set; }
public bool isPurchasable { get; set; }
public int stock { get; set; }
public string stockStatus { get; set; }
public int minDays { get; set; }
public int maxDays { get; set; }
}
public class Rai
{
public bool isAvailable { get; set; }
public bool isPurchasable { get; set; }
public int stock { get; set; }
public string stockStatus { get; set; }
public int minDays { get; set; }
public int maxDays { get; set; }
}
public class Pu1
{
public bool isAvailable { get; set; }
public bool isPurchasable { get; set; }
public int stock { get; set; }
public string stockStatus { get; set; }
public int minDays { get; set; }
public int maxDays { get; set; }
}
public class Pu2
{
public bool isAvailable { get; set; }
public bool isPurchasable { get; set; }
public int stock { get; set; }
public string stockStatus { get; set; }
public int minDays { get; set; }
public int maxDays { get; set; }
}
public class Pu3
{
public bool isAvailable { get; set; }
public bool isPurchasable { get; set; }
public int stock { get; set; }
public string stockStatus { get; set; }
public int minDays { get; set; }
public int maxDays { get; set; }
}
public class Pu4
{
public bool isAvailable { get; set; }
public bool isPurchasable { get; set; }
public int stock { get; set; }
public string stockStatus { get; set; }
public int minDays { get; set; }
public int maxDays { get; set; }
}
public class Stores
{
public Js2 js { get; set; }
public JsKioski js_kioski { get; set; }
public Oul oul { get; set; }
public Pir pir { get; set; }
public Rai rai { get; set; }
public Pu1 pu1 { get; set; }
public Pu2 pu2 { get; set; }
public Pu3 pu3 { get; set; }
public Pu4 pu4 { get; set; }
}
public class Stocks
{
public Web web { get; set; }
public Stores stores { get; set; }
}
public class Availability
{
public string _id { get; set; }
public int pid { get; set; }
public object overrideText { get; set; }
public bool isElectronic { get; set; }
public bool isVirtual { get; set; }
public bool isInStoresOnly { get; set; }
public bool isReleased { get; set; }
public bool isShippingAllowed { get; set; }
public bool isPickupAllowed { get; set; }
public bool isStockVisible { get; set; }
public bool isPurchasable { get; set; }
public bool isSoldOut { get; set; }
public bool isEOL { get; set; }
public bool isFastDeliveryAvailable { get; set; }
public bool isStoreOrderAllowed { get; set; }
public bool hasStock { get; set; }
public Stocks stocks { get; set; }
public List<object> tags { get; set; }
public DateTime updatedAt { get; set; }
public DateTime verifiedAt { get; set; }
public int updateCount { get; set; }
public DateTime updateStartTime { get; set; }
}
public class RootObject
{
public string _id { get; set; }
public bool active { get; set; }
public int ageLimit { get; set; }
public Brand brand { get; set; }
public List<string> bulletPoints { get; set; }
public List<object> bundleProducts { get; set; }
public List<object> campaigns { get; set; }
public List<string> categories { get; set; }
public Category category { get; set; }
public DateTime createdAt { get; set; }
public List<object> demoLocations { get; set; }
public string description { get; set; }
public string descriptionShort { get; set; }
public List<string> eans { get; set; }
public bool electronic { get; set; }
public Financing financing { get; set; }
public string freeShipmentFor { get; set; }
public bool hidePriceEstimate { get; set; }
public string href { get; set; }
public List<Image> images { get; set; }
public List<Link> links { get; set; }
public object maxAmountPerOrder { get; set; }
public List<string> mpns { get; set; }
public string name { get; set; }
public Package package { get; set; }
public int pid { get; set; }
public Price price { get; set; }
public string productId { get; set; }
public Rating rating { get; set; }
public Relations relations { get; set; }
public DateTime releasedAt { get; set; }
public Restrictions restrictions { get; set; }
public List<string> ribbons { get; set; }
public List<ShipmentPrice> shipmentPrices { get; set; }
public List<object> shopAreas { get; set; }
public bool vak { get; set; }
public int visible { get; set; }
public string warranty { get; set; }
public DateTime updatedAt { get; set; }
public DateTime verifiedAt { get; set; }
public int updateCount { get; set; }
public DateTime updateStartTime { get; set; }
public Availability availability { get; set; }
}
class Program
{
static void Main(string[] args)
{
string API = "https://www.verkkokauppa.com/resp-api/product?pids=552952";
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(API);
request.Method = "GET";
string result = "";
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
result = reader.ReadToEnd();
reader.Close();
dataStream.Close();
}
var jsonresult = JsonConvert.DeserializeObject<List<RootObject>>(result);
foreach (RootObject p in jsonresult)
{
foreach (var item in p.links)
{
Debug.WriteLine(item.href);
}
}
Console.WriteLine("Hello World!");
}
}
}
You can use https://quicktype.io to generate c# code with entities from JSON.
i have created the c# classes for your json request.
https://app.quicktype.io?share=KNyJfG7rGBZH96H6yNXe

Deserialize JSON to C# Object - No Data being deserialized

Found an odd issue when trying to deserialize a JSON string into a C# Object. It "seems" to perform the operation successfully (as in it does not throw any exception etc), however the outputted POCO contains does not contain any data from the JSON string, it only contains type default data (nulls,"", 0 etc). I have tried this process with other JSON and it works fine.
private string GetJson()
{
return #"{""backdrop_path"":"" / 1LrtAhWPSEetJLjblXvnaYtl7eA.jpg"",""created_by"":[{""id"":488,""name"":""Steven Spielberg"",""profile_path"":"" / pOK15UNaw75Bzj7BQO1ulehbPPm.jpg""},{""id"":31,""name"":""Tom Hanks"",""profile_path"":"" / a14CNByTYALAPSGlwlmfHILpEIW.jpg""}],""episode_run_time"":[60],""first_air_date"":""2001 - 09 - 09"",""genres"":[{""id"":28,""name"":""Action""},{""id"":12,""name"":""Adventure""},{""id"":18,""name"":""Drama""},{""id"":10752,""name"":""War""}],""homepage"":""http://www.hbo.com/band-of-brothers"",""id"":4613,""in_production"":false,""languages"":[""de"",""fr"",""lt"",""nl"",""en""],""last_air_date"":""2001-11-04"",""name"":""Band of Brothers"",""networks"":[{""id"":49,""name"":""HBO""}],""number_of_episodes"":10,""number_of_seasons"":1,""origin_country"":[""GB"",""US""],""original_language"":""en"",""original_name"":""Band of Brothers"",""overview"":""Drawn from interviews with survivors of Easy Company, as well as their journals and letters, Band of Brothers chronicles the experiences of these men from paratrooper training in Georgia through the end of the war. As an elite rifle company parachuting into Normandy early on D-Day morning, participants in the Battle of the Bulge, and witness to the horrors of war, the men of Easy knew extraordinary bravery and extraordinary fear - and became the stuff of legend. Based on Stephen E. Ambrose's acclaimed book of the same name."",""popularity"":3.435181,""poster_path"":""/bUrt6oeXd04ImEwQjO9oLjRguaA.jpg"",""production_companies"":[{""name"":""DreamWorks SKG"",""id"":27},{""name"":""HBO Films"",""id"":7429},{""name"":""DreamWorks Television"",""id"":15258}],""seasons"":[{""air_date"":null,""episode_count"":4,""id"":14071,""poster_path"":""/bMN9iiSAdnmAjflREfCCH0TTNyQ.jpg"",""season_number"":0},{""air_date"":""2001-09-09"",""episode_count"":10,""id"":14070,""poster_path"":""/15SN18OVbYt12Wzttclh51Sz9m1.jpg"",""season_number"":1}],""status"":""Ended"",""type"":""Scripted"",""vote_average"":8.5,""vote_count"":47}";
}
[TestMethod]
public void DeserializeTmdbShowData_ValidShowData_ReturnDeserializedObject()
{
//Arrange
string jsonStream = GetJson();
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
//Act
var tmdbShowDetails = jsonSerializer.Deserialize<List<TmdbShowDetailsDto>>(jsonStream);
//Assert
Assert.IsNotNull(tmdbShowDetails);
Assert.IsNotNull(tmdbShowDetails.First().backdrop_path);
}
public class TmdbShowDetailsDto
{
public string backdrop_path { get; set; }
public Created_By[] created_by { get; set; }
public int[] episode_run_time { get; set; }
public string first_air_date { get; set; }
public Genre[] genres { get; set; }
public string homepage { get; set; }
public int id { get; set; }
public bool in_production { get; set; }
public string[] languages { get; set; }
public string last_air_date { get; set; }
public string name { get; set; }
public Network[] networks { get; set; }
public int number_of_episodes { get; set; }
public int number_of_seasons { get; set; }
public string[] origin_country { get; set; }
public string original_language { get; set; }
public string original_name { get; set; }
public string overview { get; set; }
public float popularity { get; set; }
public string poster_path { get; set; }
public Production_Companies[] production_companies { get; set; }
public Season[] seasons { get; set; }
public string status { get; set; }
public string type { get; set; }
public float vote_average { get; set; }
public int vote_count { get; set; }
}
public class Created_By
{
public int id { get; set; }
public string name { get; set; }
public string profile_path { get; set; }
}
public class Genre
{
public int id { get; set; }
public string name { get; set; }
}
public class Network
{
public int id { get; set; }
public string name { get; set; }
}
public class Production_Companies
{
public string name { get; set; }
public int id { get; set; }
}
public class Season
{
public string air_date { get; set; }
public int episode_count { get; set; }
public int id { get; set; }
public string poster_path { get; set; }
public int season_number { get; set; }
}
Any ideas - Im sure I have missed something glaringly obvious but I cannot see it. Using .NET 4.5
Help appreciated.
Cheers
I used http://json2csharp.com/, and the code is like this, so you should look at it.
public class Poster
{
public string full { get; set; }
public string medium { get; set; }
public string thumb { get; set; }
}
public class Fanart
{
public string full { get; set; }
public string medium { get; set; }
public string thumb { get; set; }
}
public class Images
{
public Poster poster { get; set; }
public Fanart fanart { get; set; }
}
public class Ids
{
public int trakt { get; set; }
public string slug { get; set; }
public int tvdb { get; set; }
public string imdb { get; set; }
public int tmdb { get; set; }
public int tvrage { get; set; }
}
public class Show
{
public string title { get; set; }
public string overview { get; set; }
public int year { get; set; }
public string status { get; set; }
public Images images { get; set; }
public Ids ids { get; set; }
}
public class Poster2
{
public string full { get; set; }
public string medium { get; set; }
public string thumb { get; set; }
}
public class Fanart2
{
public string full { get; set; }
public string medium { get; set; }
public string thumb { get; set; }
}
public class Images2
{
public Poster2 poster { get; set; }
public Fanart2 fanart { get; set; }
}
public class Ids2
{
public int trakt { get; set; }
public string slug { get; set; }
public string imdb { get; set; }
public int tmdb { get; set; }
}
public class Movie
{
public string title { get; set; }
public string overview { get; set; }
public int year { get; set; }
public Images2 images { get; set; }
public Ids2 ids { get; set; }
}
public class Headshot
{
public object full { get; set; }
public object medium { get; set; }
public object thumb { get; set; }
}
public class Images3
{
public Headshot headshot { get; set; }
}
public class Ids3
{
public int trakt { get; set; }
public string slug { get; set; }
public string imdb { get; set; }
public int tmdb { get; set; }
public int tvrage { get; set; }
}
public class Person
{
public string name { get; set; }
public Images3 images { get; set; }
public Ids3 ids { get; set; }
}
public class RootObject
{
public string type { get; set; }
public object score { get; set; }
public Show show { get; set; }
public Movie movie { get; set; }
public Person person { get; set; }
}
You can use Paste-Special Feature in your VS-IDE Paster JSON as Classes
public class Rootobject
{
public Class1[] Property1 { get; set; }
}
public class Class1
{
public string type { get; set; }
public object score { get; set; }
public Show show { get; set; }
public Movie movie { get; set; }
public Person person { get; set; }
}
public class Show
{
public string title { get; set; }
public string overview { get; set; }
public int year { get; set; }
public string status { get; set; }
public Images images { get; set; }
public Ids ids { get; set; }
}
public class Images
{
public Poster poster { get; set; }
public Fanart fanart { get; set; }
}
public class Poster
{
public string full { get; set; }
public string medium { get; set; }
public string thumb { get; set; }
}
public class Fanart
{
public string full { get; set; }
public string medium { get; set; }
public string thumb { get; set; }
}
public class Ids
{
public int trakt { get; set; }
public string slug { get; set; }
public int tvdb { get; set; }
public string imdb { get; set; }
public int tmdb { get; set; }
public int tvrage { get; set; }
}
public class Movie
{
public string title { get; set; }
public string overview { get; set; }
public int year { get; set; }
public Images1 images { get; set; }
public Ids1 ids { get; set; }
}
public class Images1
{
public Poster1 poster { get; set; }
public Fanart1 fanart { get; set; }
}
public class Poster1
{
public string full { get; set; }
public string medium { get; set; }
public string thumb { get; set; }
}
public class Fanart1
{
public string full { get; set; }
public string medium { get; set; }
public string thumb { get; set; }
}
public class Ids1
{
public int trakt { get; set; }
public string slug { get; set; }
public string imdb { get; set; }
public int tmdb { get; set; }
}
public class Person
{
public string name { get; set; }
public Images2 images { get; set; }
public Ids2 ids { get; set; }
}
public class Images2
{
public Headshot headshot { get; set; }
}
public class Headshot
{
public object full { get; set; }
public object medium { get; set; }
public object thumb { get; set; }
}
public class Ids2
{
public int trakt { get; set; }
public string slug { get; set; }
public string imdb { get; set; }
public int tmdb { get; set; }
public int tvrage { get; set; }
}
Look like you JSON string is not in correct format that you are trying to deserialize. For example i have not find show property in the C# class but it present in JSON.
So this issue I couldn't figure out in the night or early in the morning - it took me till this afternoon until I realised that I was had the wrong JSON!!, so no wonder it wasn't working! I got mixed up with a few different apis that provided JSON. Thanks to those who had pointed out that the class looks wrong, made me double check my code and realise the simplicity of this issue. Kinda needed some rubber ducking to spot the problem. Cheers

Newtonsoft.Json empty object after deserialization

I'm trying to deserialize JSON from a url using the following code. I'm getting an empty object even though I'm downloading a valid JSON string.
public static void tryjson() {
string json = new WebClient().DownloadString("http://www.sofascore.com/football/livescore/json");
SportItem sportItem = JsonConvert.DeserializeObject<SportItem>(json);
}
Classes:
public class Sport {
public int id { get; set; }
public string name { get; set; }
public string slug { get; set; }
}
public class Tournament2 {
public int id { get; set; }
public string name { get; set; }
public string slug { get; set; }
public int priority { get; set; }
public int order { get; set; }
public int uniqueId { get; set; }
public string uniqueName { get; set; }
}
public class Category {
public int id { get; set; }
public string name { get; set; }
public string slug { get; set; }
public int priority { get; set; }
public List<object> mcc { get; set; }
public string flag { get; set; }
}
public class Season {
public int id { get; set; }
public string name { get; set; }
public string slug { get; set; }
public string year { get; set; }
}
public class HomeScore {
public int current { get; set; }
public int period1 { get; set; }
public int normaltime { get; set; }
public int? aggregated { get; set; }
public int? penalties { get; set; }
public int? overtime { get; set; }
}
public class AwayScore {
public int current { get; set; }
public int period1 { get; set; }
public int normaltime { get; set; }
public int? aggregated { get; set; }
public int? penalties { get; set; }
public int? overtime { get; set; }
}
public class Status {
public int code { get; set; }
public string type { get; set; }
}
public class Changes {
public string changeDate { get; set; }
public List<object> changes { get; set; }
public int changeTimestamp { get; set; }
public bool hasExpired { get; set; }
public bool hasHomeChanges { get; set; }
public bool hasAwayChanges { get; set; }
}
public class RoundInfo {
public int round { get; set; }
public string name { get; set; }
}
public class Sport2 {
public int id { get; set; }
public string name { get; set; }
public string slug { get; set; }
}
public class HomeTeam {
public int id { get; set; }
public string name { get; set; }
public string slug { get; set; }
public string gender { get; set; }
public List<object> subTeams { get; set; }
}
public class AwayTeam {
public int id { get; set; }
public string name { get; set; }
public string slug { get; set; }
public string gender { get; set; }
public List<object> subTeams { get; set; }
}
public class Odds {
public int id { get; set; }
public double odds1 { get; set; }
public double oddsX { get; set; }
public double odds2 { get; set; }
public double odds1X { get; set; }
public double oddsX2 { get; set; }
public double odds12 { get; set; }
public double liveOdds1 { get; set; }
public double liveOddsX { get; set; }
public double liveOdds2 { get; set; }
public double liveOdds1X { get; set; }
public double liveOddsX2 { get; set; }
public double liveOdds12 { get; set; }
public string fractionalOdds1 { get; set; }
public string fractionalOddsX { get; set; }
public string fractionalOdds2 { get; set; }
public string fractionalOdds1X { get; set; }
public string fractionalOddsX2 { get; set; }
public string fractionalOdds12 { get; set; }
public string liveFractionalOdds1 { get; set; }
public string liveFractionalOddsX { get; set; }
public string liveFractionalOdds2 { get; set; }
public string liveFractionalOdds1X { get; set; }
public string liveFractionalOddsX2 { get; set; }
public string liveFractionalOdds12 { get; set; }
public string americanOdds1 { get; set; }
public string americanOddsX { get; set; }
public string americanOdds2 { get; set; }
public string americanOdds1X { get; set; }
public string americanOddsX2 { get; set; }
public string americanOdds12 { get; set; }
public string liveAmericanOdds1 { get; set; }
public string liveAmericanOddsX { get; set; }
public string liveAmericanOdds2 { get; set; }
public string liveAmericanOdds1X { get; set; }
public string liveAmericanOddsX2 { get; set; }
public string liveAmericanOdds12 { get; set; }
public int odds1Change { get; set; }
public int oddsXChange { get; set; }
public int odds2Change { get; set; }
public int odds1XChange { get; set; }
public int oddsX2Change { get; set; }
public int odds12Change { get; set; }
public string bet365OddsId1 { get; set; }
public string bet365OddsIdX { get; set; }
public string bet365OddsId2 { get; set; }
public string bet365OddsId1X { get; set; }
public string bet365OddsIdX2 { get; set; }
public string bet365OddsId12 { get; set; }
public string betSlipLink1 { get; set; }
public string betSlipLinkX { get; set; }
public string betSlipLink2 { get; set; }
public string betSlipLink1X { get; set; }
public string betSlipLinkX2 { get; set; }
public string betSlipLink12 { get; set; }
public bool liveOddsEnabled { get; set; }
public bool liveDoubleChanceOddsEnabled { get; set; }
}
public class Event {
public int id { get; set; }
public string customId { get; set; }
public HomeScore homeScore { get; set; }
public AwayScore awayScore { get; set; }
public Status status { get; set; }
public int winnerCode { get; set; }
public Changes changes { get; set; }
public RoundInfo roundInfo { get; set; }
public Sport2 sport { get; set; }
public HomeTeam homeTeam { get; set; }
public AwayTeam awayTeam { get; set; }
public Odds odds { get; set; }
public bool hasHighlights { get; set; }
public bool hasHighlightsStream { get; set; }
public bool hasEventPlayerStatistics { get; set; }
public bool hasEventPlayerHeatMap { get; set; }
public int rowCount { get; set; }
public int homeRedCards { get; set; }
public int awayRedCards { get; set; }
public string statusDescription { get; set; }
public bool hasLiveForm { get; set; }
public string name { get; set; }
public string startTime { get; set; }
public string formatedStartDate { get; set; }
public int startTimestamp { get; set; }
public string slug { get; set; }
public bool hasLineupsList { get; set; }
public bool hasOdds { get; set; }
public bool hasLiveOdds { get; set; }
public bool hasFirstToServe { get; set; }
public bool hasDraw { get; set; }
public bool isSyncable { get; set; }
public int? aggregatedWinnerCode { get; set; }
}
public class Tournament {
public Tournament2 tournament { get; set; }
public Category category { get; set; }
public Season season { get; set; }
public bool hasEventPlayerStatistics { get; set; }
public bool hasEventPlayerHeatMap { get; set; }
public List<Event> events { get; set; }
}
public class SportItem {
public Sport sport { get; set; }
public int rows { get; set; }
public List<Tournament> tournaments { get; set; }
}
public class Params {
public string sport { get; set; }
public object category { get; set; }
public string date { get; set; }
}
public class RootObject {
public SportItem sportItem { get; set; }
public Params #params { get; set; }
public bool isShortDate { get; set; }
}
What am I doing wrong?
Try this:
System.Net.WebClient wc = new System.Net.WebClient();
wc.DownloadStringCompleted += (s, u) =>
{
DownloadStringCompleted(s, u);
};
wc.DownloadStringAsync(new Uri("http://www.sofascore.com/football/livescore/json"));
private void DownloadStringCompleted(object s, DownloadStringCompletedEventArgs u)
{
try
{
var Item = JsonConvert.DeserializeObject<RootObject>(u.Result.ToString());
}
catch (Exception ex)
{ }
}
It looks like you need to parse into the json object first. Example:-
var data = (JObject)JsonConvert.DeserializeObject(resultJson);

How to parse Json from the RootObject?

I am trying to parse JSON response so I created some classes.
Actually I want Leg and Flight class element value. I am trying to get those element value from RootObject but I don't know how to do this. I googled but I am little bit confuse.
I paste my JSON respose , Classes !!
JSON Response :
http://pastebin.com/fjjLxkd2
Classes :
public class Detail
{
}
public class Airport
{
public string kind { get; set; }
public string code { get; set; }
public string city { get; set; }
public string name { get; set; }
}
public class City
{
public string kind { get; set; }
public string code { get; set; }
public string name { get; set; }
}
public class Aircraft
{
public string kind { get; set; }
public string code { get; set; }
public string name { get; set; }
}
public class Tax
{
public string kind { get; set; }
public string id { get; set; }
public string name { get; set; }
}
public class Carrier
{
public string kind { get; set; }
public string code { get; set; }
public string name { get; set; }
}
public class Data
{
public string kind { get; set; }
public List<Airport> airport { get; set; }
public List<City> city { get; set; }
public List<Aircraft> aircraft { get; set; }
public List<Tax> tax { get; set; }
public List<Carrier> carrier { get; set; }
}
public class Flight
{
public string carrier { get; set; }
public string number { get; set; }
}
public class Leg
{
public string kind { get; set; }
public string id { get; set; }
public string aircraft { get; set; }
public string arrivalTime { get; set; }
public string departureTime { get; set; }
public string origin { get; set; }
public string destination { get; set; }
public string originTerminal { get; set; }
public int duration { get; set; }
public int onTimePerformance { get; set; }
public int mileage { get; set; }
public string meal { get; set; }
public bool secure { get; set; }
public string destinationTerminal { get; set; }
public string operatingDisclosure { get; set; }
}
public class Segment
{
public string kind { get; set; }
public int duration { get; set; }
public Flight flight { get; set; }
public string id { get; set; }
public string cabin { get; set; }
public string bookingCode { get; set; }
public int bookingCodeCount { get; set; }
public string marriedSegmentGroup { get; set; }
public List<Leg> leg { get; set; }
public int connectionDuration { get; set; }
}
public class Slouse
{
public string kind { get; set; }
public int duration { get; set; }
public List<Segment> segment { get; set; }
}
public class Fare
{
public string kind { get; set; }
public string id { get; set; }
public string carrier { get; set; }
public string origin { get; set; }
public string destination { get; set; }
public string basisCode { get; set; }
}
public class BagDescriptor
{
public string kind { get; set; }
public string commercialName { get; set; }
public int count { get; set; }
public string subcode { get; set; }
public List<string> description { get; set; }
}
public class FreeBaggageOption
{
public string kind { get; set; }
public List<BagDescriptor> bagDescriptor { get; set; }
public int pieces { get; set; }
}
public class SegmentPricing
{
public string kind { get; set; }
public string fareId { get; set; }
public string segmentId { get; set; }
public List<FreeBaggageOption> freeBaggageOption { get; set; }
}
public class Passengers
{
public string kind { get; set; }
public int adultCount { get; set; }
}
public class Tax2
{
public string kind { get; set; }
public string id { get; set; }
public string chargeType { get; set; }
public string code { get; set; }
public string country { get; set; }
public string salePrice { get; set; }
}
public class Pricing
{
public string kind { get; set; }
public List<Fare> fare { get; set; }
public List<SegmentPricing> segmentPricing { get; set; }
public string baseFareTotal { get; set; }
public string saleFareTotal { get; set; }
public string saleTaxTotal { get; set; }
public string saleTotal { get; set; }
public Passengers passengers { get; set; }
public List<Tax2> tax { get; set; }
public string fareCalculation { get; set; }
public string latestTicketingTime { get; set; }
public string ptc { get; set; }
}
public class TripOption
{
public string kind { get; set; }
public string saleTotal { get; set; }
public string id { get; set; }
public List<Slouse> slice { get; set; }
public List<Pricing> pricing { get; set; }
}
public class Trips
{
public string kind { get; set; }
public string requestId { get; set; }
public Data data { get; set; }
public List<TripOption> tripOption { get; set; }
}
public class RootObject
{
public string kind { get; set; }
public Trips trips { get; set; }
}
Code :
var obj0 = JsonConvert.DeserializeObject<RootObject>(responsedata);
Here I got only Trip class element . I want the Leg and Flight class element.
If you want to find information for a specific leg, you need to use Linq to traverse the tree. For example, if you just know the leg id, you could do something like this:
var allLegs = obj0.trips.tripOption.SelectMany(to => to.slice.SelectMany(sl => sl.segment.Select(sg => sg.leg)));
var leg = allLegs.FirstOrDefault(l => l.id == "yourId");
The query for retrieving a flight would be similar. You could also filter by tripOption id to get a specific tripOption and then retrieve flights or legs that are associated with it.

deserializing an object with a generic list

I am trying to deserialize an object, the type is populated but I am getting null for the List<Sport>. Any ideas?
My classes:
class Sports
{
public MsgTypes type { get; set; }
public List<Sport> Sport { get; set; }
}
class Sport
{
public int Id { get; set; }
public int Import_id { get; set; }
public string Name { get; set; }
public int Active { get; set; }
public int Order { get; set; }
public int Min_bet { get; set; }
public int Max_bet { get; set; }
public int Updated { get; set; }
public string Feed_type { get; set; }
public string Locale { get; set; }
}
The command for deserialization:
Sports _sports = (Sports) JsonConvert.DeserializeObject<Sports>(jsonObj);
This is my JSON object:
"{\"code\":0,\"type\":4,\"Sports\":[{\"Sport\":{\"id\":\"1\",\"import_id\":\"1\",\"name\":\"Soccer\",\"active\":true,\"order\":\"1\",\"min_bet\":\"0\",\"max_bet\":\"0\",\"updated\":\"1403194889\",\"feed_type\":\"Betradar\",\"locale\":\"en_us\"}},{\"Sport\":{\"id\":\"2\",\"import_id\":\"5\",\"name\":\"Tennis\",\"active\":true,\"order\":\"3\",\"min_bet\":\"0\",\"max_bet\":\"0\",\"updated\":\"1403194771\",\"feed_type\":\"Betradar\",\"locale\":\"en_us\"}},{\"Sport\":{\"id\":\"3\",\"import_id\":\"6\",\"name\":\"Handball\",\"active\":true,\"order\":\"6\",\"min_bet\":\"0\",\"max_bet\":\"0\",\"updated\":\"1403152901\",\"feed_type\":\"Betradar\",\"locale\":\"en_us\"}},{\"Sport\":{\"id\":\"4\",\"import_id\":\"4\",\"name\":\"Ice Hockey\",\"active\":true,\"order\":\"4\",\"min_bet\":\"0\",\"max_bet\":\"0\",\"updated\":\"1403080245\",\"feed_type\":\"Betradar\",\"locale\":\"en_us\"}},{\"Sport\":{\"id\":\"7\",\"import_id\":\"2\",\"name\":\"Basketball\",\"active\":true,\"order\":\"2\",\"min_bet\":\"0\",\"max_bet\":\"0\",\"updated\":\"1403194830\",\"feed_type\":\"Betradar\",\"locale\":\"en_us\"}},{\"Sport\":{\"id\":\"8\",\"import_id\":\"23\",\"name\":\"Volleyball\",\"active\":true,\"order\":\"5\",\"min_bet\":\"0\",\"max_bet\":\"0\",\"updated\":\"1403194591\",\"feed_type\":\"Betradar\",\"locale\":\"en_us\"}},{\"Sport\":{\"id\":\"9\",\"import_id\":\"12\",\"name\":\"Rugby\",\"active\":true,\"order\":\"7\",\"min_bet\":\"0\",\"max_bet\":\"0\",\"updated\":\"1403194710\",\"feed_type\":\"Betradar\",\"locale\":\"en_us\"}},{\"Sport\":{\"id\":\"12\",\"import_id\":\"11\",\"name\":\"Motorsport\",\"active\":true,\"order\":\"12\",\"min_bet\":\"0\",\"max_bet\":\"0\",\"updated\":\"1403065699\",\"feed_type\":\"Betradar\",\"locale\":\"en_us\"}},{\"Sport\":{\"id\":\"13\",\"import_id\":\"3\",\"name\":\"Baseball\",\"active\":true,\"order\":\"13\",\"min_bet\":\"0\",\"max_bet\":\"0\",\"updated\":\"1403194834\",\"feed_type\":\"Betradar\",\"locale\":\"en_us\"}},{\"Sport\":{\"id\":\"14\",\"import_id\":\"16\",\"name\":\"American Football\",\"active\":true,\"order\":\"14\",\"min_bet\":\"0\",\"max_bet\":\"0\",\"updated\":\"1403143326\",\"feed_type\":\"Betradar\",\"locale\":\"en_us\"}},{\"Sport\":{\"id\":\"16\",\"import_id\":\"34\",\"name\":\"Beach Volley\",\"active\":true,\"order\":\"16\",\"min_bet\":\"0\",\"max_bet\":\"0\",\"updated\":\"1403194417\",\"feed_type\":\"Betradar\",\"locale\":\"en_us\"}}]}"
You need one more level of nesting and different class names. You should be able to deserialize to such structure:
class SportsParent
{
//Code for MsgTypes was not provided so it is commented out
public List<SportGroup> Sports { get; set; }
}
class SportGroup
{
public SportItem Sport { get; set; }
}
class SportItem
{
public int Id { get; set; }
public int Import_id { get; set; }
public string Name { get; set; }
public bool Active { get; set; } //need to be converted to bool instead of int
public int Order { get; set; }
public int Min_bet { get; set; }
public int Max_bet { get; set; }
public int Updated { get; set; }
public string Feed_type { get; set; }
public string Locale { get; set; }
}
You can deserialize using such code:
SportsParent _sports = JsonConvert.DeserializeObject<SportsParent>(jsonObj);

Categories