using some types in multiple classes - c#

I have a class like:
public class Soru
{
public void SoruKaydet(){...}
private static void SoruEtiketKaydet(Guid soruId, Etiket etiket, DbManager db){...}
public Guid? SoruId { get; set; }
public Guid? SoranId { get; set; }
public int? BakilmaSayisi { get; set; }
public string HtmlGovde { get; set; }
public string MarkdownGovde { get; set; }
public string Baslik { get; set; }
public int? KategoriId { get; set; }
public DateTime OlusturulmaTarihi { get; set; }
public List<Etiket> Etiketler { get; set; }
}
I need another class should contain some of variables in class "Soru". I have two scenario for this.
The first scenario:
public class SoruSayfa
{
public static List<SoruSayfa> SoruSayfaGetir(){...}
public Guid? SoruId { get; set; }
public Guid? SoranId { get; set; }
public int? BakilmaSayisi { get; set; }
public string Baslik { get; set; }
public int? KategoriId { get; set; }
public int DurumId { get; set; }
public double SoruPuani { get; set; }
public int CevapSayisi { get; set; }
public int BakilmaSayisi { get; set; }
public string KullaniciAdi { get; set; }
public double? KisiAlanPuani { get; set; }
}
The second scenario:
public class SoruSayfa
{
public static List<SoruSayfa> SoruSayfaGetir(){...}
// Refers the class Soru instead of some variables of it
public Soru MySoru { get; set; }
public int DurumId { get; set; }
public double SoruPuani { get; set; }
public int CevapSayisi { get; set; }
public int BakilmaSayisi { get; set; }
public string KullaniciAdi { get; set; }
public double? KisiAlanPuani { get; set; }
}
In first scenario, there is not extra variable which is not used, but in second scenario some variables of MySoru is not used(HtmlGovde, MarkdownGovde, OlusturulmaTarihi, Etiketler). In addition, Soru and SoruSayfa classes will be used as model for different actions in asp .net MVC. They contain different methods. Which scenario is better?

Try a third scenario ;)
public class SoruBase
{
public Guid? SoruId { get; set; }
public Guid? SoranId { get; set; }
public int? BakilmaSayisi { get; set; }
public string Baslik { get; set; }
public int? KategoriId { get; set; }
}
public class Soru : SoruBase
{
public string HtmlGovde { get; set; }
public string MarkdownGovde { get; set; }
public DateTime OlusturulmaTarihi { get; set; }
public List<Etiket> Etiketler { get; set; }
}
public class SoruSayfa : SoruBase
{
public int DurumId { get; set; }
public double SoruPuani { get; set; }
public int CevapSayisi { get; set; }
public int BakilmaSayisi { get; set; }
public string KullaniciAdi { get; set; }
public double? KisiAlanPuani { get; set; }
}

Related

How can I convert a StringContent() type to an object of type <MyModelClass> in C# with Visual Studio 2019

I'm trying to turn the string result below in the first line of code into an object of type "Root.cs". I have "Root.cs" class set up in my Visual Studio 2019 "solution" with proper classes set up to turn the string result into the object.
This line of code works fine to get me the string I need:
var result = client.PostAsync(endpoint, payload).Result.Content.ReadAsStringAsync().Result;
Here's the contents of the string "result":
{"sections":[{"id":"Building_Configuration","name":"Building_Configuration","sections":[{"id":"B uilding_Configuration.Parameters_SP","name":"Building_Configuration.Parameters_SP","sectio ns":[],"variables":[{"id":"Building_Configuration.Parameters_SP.fixtureStrategy_SP","name":"Bui lding_Configuration.Parameters_SP.fixtureStrategy_SP","valueType":"String","distinctValueCou nt":3.0,"allowMultipleAssignments":false,"values":[{"name":"ETA","value":"ETA","properties":[{ "id":"fullyqualifiedname","value":"ETA","type":"String"},{"id":"name","value":"ETA","type":"Stri ng"}],"type":"SingletonValue","assigned":"byDefault","incompatible":false},{"name":"ETD","valu e":"ETD","properties":[{"id":"fullyqualifiedname","value":"ETD","type":"String"},{"id":"name","v alue":"ETD","type":"String"}],"type":"SingletonValue","incompatible":false},{"name":"ETA/ETD", "value":"ETA/ETD","properties":[{"id":"fullyqualifiedname","value":"ETA/ETD","type":"String"},{ "id":"name","value":"ETA/ETD","type":"String"}],"type":"SingletonValue","incompatible":false}],"
Now, I need to create the object of type "Root" (My Model Class) for the purpose of picking and choosing certain values out of it. Shouldn't this line work for that?
Root MyObject = JsonConvert.DeserializeObject<Root>(result);
Here's the definition of Root.cs:
public class Root
{
public List<Sections> sections { get; set; }
public RemovedAssignments removedAssignments { get; set; }
public Arguments arguments { get; set; }
public bool isComplete { get; set; }
public bool isConfigurable { get; set; }
public Debug debug { get; set; }
public string language { get; set; }
public string packagePath { get; set; }
}
public class Sections
{
public string id { get; set; }
public string name { get; set; }
public List<Sections> sections { get; set; }
public List<Variable> variables { get; set; }
public List<Property> properties { get; set; }
}
public class RemovedAssignments
{
public List<VariableAssignment> variableAssignments { get; set; }
public List<object> priceLineAssignments { get; set; }
}
public class Debug
{
public List<ScriptError> scriptError { get; set; }
}
public class Property
{
public string id { get; set; }
public string value { get; set; }
public string type { get; set; }
}
public class ScriptError
{
public string scriptName { get; set; }
public string Error { get; set; }
}
public class Value
{
public string name { get; set; }
public object value { get; set; }
public List<Property> properties { get; set; }
public string type { get; set; }
public string assigned { get; set; }
public bool incompatible { get; set; }
public double? lower { get; set; }
public double? upper { get; set; }
}
public class Value3
{
public string value { get; set; }
public string name { get; set; }
public bool exclude { get; set; }
}
public class Variable
{
public string id { get; set; }
public string name { get; set; }
public string valueType { get; set; }
public double distinctValueCount { get; set; }
public bool allowMultipleAssignments { get; set; }
public List<Value> values { get; set; }
public List<Property> properties { get; set; }
}
public class Variable3
{
public string id { get; set; }
public string name { get; set; }
public string valueType { get; set; }
public bool allowMultipleAssignments { get; set; }
}
public class VariableAssignment
{
public Variable variable { get; set; }
public Value value { get; set; }
}
public class Arguments
{
public Configuration Configuration { get; set; }
}
public class Configuration
{
[JsonProperty("Building_Configuration.Parameters_SP.fixtureStrategy_SP")]
public string BuildingConfigurationParametersSPFixtureStrategySP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.dimensionSelection_SP")]
public string BuildingConfigurationParametersSPDimensionSelectionSP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.controllerRobotic_SP")]
public bool BuildingConfigurationParametersSPControllerRoboticSP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.controllerBACNet_SP")]
public bool BuildingConfigurationParametersSPControllerBACNetSP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.digitalPI_SP")]
public string BuildingConfigurationParametersSPDigitalPISP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.interGroupEmergencyPower_SP")]
public string BuildingConfigurationParametersSPInterGroupEmergencyPowerSP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.customJewel_SP")]
public string BuildingConfigurationParametersSPCustomJewelSP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.loweringSequenceJewel_SP")]
public string BuildingConfigurationParametersSPLoweringSequenceJewelSP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.inServiceJewel_SP")]
public string BuildingConfigurationParametersSPInServiceJewelSP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.cat5CableFeetRequired_SP")]
public int BuildingConfigurationParametersSPCat5CableFeetRequiredSP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.fiberOpticConnectorsSetOf4_SP")]
public int BuildingConfigurationParametersSPFiberOpticConnectorsSetOf4SP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.cGADevices_SP")]
public int BuildingConfigurationParametersSPCGADevicesSP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.fiberOpticCableFeetRequired_SP")]
public int BuildingConfigurationParametersSPFiberOpticCableFeetRequiredSP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.qtyOfGatewayForLiftNet_SP")]
public int BuildingConfigurationParametersSPQtyOfGatewayForLiftNetSP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.qtyOfGroupEthernetBoxWIMSSoftwareOnly_SP")]
public int BuildingConfigurationParametersSPQtyOfGroupEthernetBoxWIMSSoftwareOnlySP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.interGroupStarBox_SP")]
public int BuildingConfigurationParametersSPInterGroupStarBoxSP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.mediaConverterAndPowerSource_SP")]
public int BuildingConfigurationParametersSPMediaConverterAndPowerSourceSP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.qtyOfSoftwareSiteKeyJBFiles_SP")]
public int BuildingConfigurationParametersSPQtyOfSoftwareSiteKeyJBFilesSP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.doorOpenSignalJewel_SP")]
public bool BuildingConfigurationParametersSPDoorOpenSignalJewelSP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.mountingProvisionsForMonitor_SP")]
public bool BuildingConfigurationParametersSPMountingProvisionsForMonitorSP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.intercomSpace_SP")]
public bool BuildingConfigurationParametersSPIntercomSpaceSP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.specialEngraving_SP")]
public bool BuildingConfigurationParametersSPSpecialEngravingSP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.lobbyPanelFinish_SP")]
public string BuildingConfigurationParametersSPLobbyPanelFinishSP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.includeAGILEDesignCenter_SP")]
public int BuildingConfigurationParametersSPIncludeAGILEDesignCenterSP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.qtyKiosksOver300Ft_SP")]
public int BuildingConfigurationParametersSPQtyKiosksOver300FtSP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.dDSecurityInterfaceType_SP")]
public bool BuildingConfigurationParametersSPDDSecurityInterfaceTypeSP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.iMSOwnersStandard_SP")]
public int BuildingConfigurationParametersSPIMSOwnersStandardSP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.qtyOfIMSOwnersEnhanced_SP")]
public int BuildingConfigurationParametersSPQtyOfIMSOwnersEnhancedSP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.totalGroupHallStation_SP")]
public int BuildingConfigurationParametersSPTotalGroupHallStationSP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.totalUnitHallStation_SP")]
public int BuildingConfigurationParametersSPTotalUnitHallStationSP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.totalBuildingEquip_SP")]
public int BuildingConfigurationParametersSPTotalBuildingEquipSP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.IsSmartRescue10_Bool_SP")]
public bool BuildingConfigurationParametersSPIsSmartRescue10BoolSP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.IsSmartRescue5_Bool_SP")]
public bool BuildingConfigurationParametersSPIsSmartRescue5BoolSP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.lobbyPanel_SP")]
public string BuildingConfigurationParametersSPLobbyPanelSP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.qtyOfSmartRescuePhone10_StndAlone_SP")]
public int BuildingConfigurationParametersSPQtyOfSmartRescuePhone10StndAloneSP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.qtyOfSmartRescuePhone5_Lobby_SP")]
public int BuildingConfigurationParametersSPQtyOfSmartRescuePhone5LobbySP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.qtyOfSmartRescuePhone5_StndAlone_SP")]
public int BuildingConfigurationParametersSPQtyOfSmartRescuePhone5StndAloneSP { get; set; }
[JsonProperty("Building_Configuration.Parameters_SP.qtyOfSmartRescuePhone10_Lobby_SP")]
public int BuildingConfigurationParametersSPQtyOfSmartRescuePhone10LobbySP { get; set; }
[JsonProperty("Building_Configuration.Parameters.ASYEAR_INT")]
public int BuildingConfigurationParametersASYEARINT { get; set; }
[JsonProperty("Building_Configuration.Parameters.BLANDINGS")]
public int BuildingConfigurationParametersBLANDINGS { get; set; }
[JsonProperty("Building_Configuration.Parameters.ASTYPE")]
public string BuildingConfigurationParametersASTYPE { get; set; }
[JsonProperty("Building_Configuration.Parameters.ASYEAR")]
public string BuildingConfigurationParametersASYEAR { get; set; }
[JsonProperty("Building_Configuration.Parameters.BLDGNAME")]
public string BuildingConfigurationParametersBLDGNAME { get; set; }
[JsonProperty("Building_Configuration.Parameters.IBCSDS")]
public int BuildingConfigurationParametersIBCSDS { get; set; }
[JsonProperty("Building_Configuration.Parameters.ELEVBASE")]
public int BuildingConfigurationParametersELEVBASE { get; set; }
[JsonProperty("Building_Configuration.Parameters.SEISZONE")]
public string BuildingConfigurationParametersSEISZONE { get; set; }
[JsonProperty("Building_Configuration.Parameters.SEISEQUIP")]
public string BuildingConfigurationParametersSEISEQUIP { get; set; }
[JsonProperty("Building_Configuration.Parameters.ISSEISMIC")]
public string BuildingConfigurationParametersISSEISMIC { get; set; }
[JsonProperty("Building_Configuration.Parameters.IBCSDC")]
public string BuildingConfigurationParametersIBCSDC { get; set; }
[JsonProperty("Building_Configuration.Parameters.IBCIP")]
public string BuildingConfigurationParametersIBCIP { get; set; }
[JsonProperty("Building_Configuration.Parameters.NBCCPDB")]
public string BuildingConfigurationParametersNBCCPDB { get; set; }
[JsonProperty("Building_Configuration.Parameters.NBCCIE")]
public int BuildingConfigurationParametersNBCCIE { get; set; }
[JsonProperty("Building_Configuration.Parameters.NBCCFA")]
public int BuildingConfigurationParametersNBCCFA { get; set; }
[JsonProperty("Building_Configuration.Parameters.NBCCSA02")]
public int BuildingConfigurationParametersNBCCSA02 { get; set; }
[JsonProperty("Building_Configuration.Parameters.BLDGCODE")]
public string BuildingConfigurationParametersBLDGCODE { get; set; }
[JsonProperty("Building_Configuration.Parameters.HALLFIN")]
public string BuildingConfigurationParametersHALLFIN { get; set; }
[JsonProperty("Building_Configuration.Parameters.MRP")]
public string BuildingConfigurationParametersMRP { get; set; }
[JsonProperty("Building_Configuration.Parameters.HALLMAT")]
public string BuildingConfigurationParametersHALLMAT { get; set; }
My "result" and my "Root.cs" class are each larger than the 30,000 characters limit here. So, I've had to only post a portion of my string "result" and my "Root.cs" class. I'm trying to simplify this question. Please forgive me while I learn how to use this...
Answer: I was making the newbie mistake of trying to return a string that I picked out of a "Root.cs" Model class as a Root object. I had the return type of the method set to Root instead of string. Upon changing the return type to string, that part of my solution works fine.
It works fine like this:
public string CreateExecPost(FormData person2){
var payload = new StringContent(newPost, Encoding.UTF8, "application/json");
var result = client.PostAsync(endpoint, payload).Result.Content.ReadAsStringAsync().Result;//result is already in JSON
Root MyObject = JsonConvert.DeserializeObject<Root>(result);
//return MyObject.language; //WORKS
return MyObject.language;
}

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

Get converter value {null} from path 'track[40].like_count?

An exception of type
'Newtonsoft.Json.JsonSerializationException' occurred in
Newtonsoft.Json.DLL but was not handled in user code
Additional information: Error converting value {null} to type
'System.Boolean'. Path 'collection[8].downloadable', line 1, position
22866.
or
converter value {null} from path 'track[40].like_count
?
I use Json. How to fix it?
public class User
{
public string full_name { get; set; }
public string country { get; set; }
public string city { get; set; }
public int tracks_count { get; set; }
public int followers_count { get; set; }
public int followings_count { get; set; }
public int public_favorites_count { get; set; }
public int groups_count { get; set; }
public string description { get; set; }
public string plan { get; set; }
public int id { get; set; }
public string uri { get; set; }
public string username { get; set; }
public string kind { get; set; }
public string permalink { get; set; }
public string permalink_url { get; set; }
public string first_name { get; set; }
public string avatar_url { get; set; }
public string last_modified { get; set; }
}
public class __invalid_type__0
{
public string urn { get; set; }
public int entry_time { get; set; }
public string visual_url { get; set; }
public object link { get; set; }
}
public class Visuals2
{
public __invalid_type__0 __invalid_name__0 { get; set; }
}
public class Visuals
{
public string urn { get; set; }
public bool enabled { get; set; }
public Visuals2 visuals { get; set; }
public object tracking { get; set; }
}
public class Collection
{
public User user { get; set; }
public int user_id { get; set; }
public string genre { get; set; }
public string tag_list { get; set; }
public int duration { get; set; }
public bool downloadable { get; set; }
public bool streamable { get; set; }
public int original_content_size { get; set; }
public bool commentable { get; set; }
public string sharing { get; set; }
public bool #public { get; set; }
public string created_at { get; set; }
public string updated_at { get; set; }
public string isrc { get; set; }
public string state { get; set; }
public bool embeddable { get; set; }
public string embeddable_by { get; set; }
public string license { get; set; }
public string waveform_url { get; set; }
public bool feedable { get; set; }
public string label_name { get; set; }
public string release_date { get; set; }
public bool has_downloads_left { get; set; }
public string purchase_title { get; set; }
public string purchase_url { get; set; }
public string policy { get; set; }
public string monetization_model { get; set; }
public Visuals visuals { get; set; }
public string permalink { get; set; }
public string title { get; set; }
public string description { get; set; }
public string track_type { get; set; }
public string last_modified { get; set; }
public string artwork_url { get; set; }
public int id { get; set; }
public string kind { get; set; }
public int comment_count { get; set; }
public int download_count { get; set; }
public string uri { get; set; }
public string stream_url { get; set; }
public int playback_count { get; set; }
public string download_url { get; set; }
public object secret_token { get; set; }
public int reposts_count { get; set; }
public string permalink_url { get; set; }
public int likes_count { get; set; }
}
public class Facet2
{
public string filter { get; set; }
public int count { get; set; }
public string value { get; set; }
}
public class Facet
{
public string name { get; set; }
public List<Facet2> facets { get; set; }
}
public class RootObject
{
public List<Collection> collection { get; set; }
public List<Facet> facets { get; set; }
public int total_results { get; set; }
public string qid { get; set; }
public string query_urn { get; set; }
public string next_href { get; set; }
}

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.

Categories