Getting Object reference not set to an instance of an object C#? - c#

i am getting Getting Object reference not set to an instance of an object error
my code and the image are attached below
public class Backlogitem
{
public string Name { get; set; }
public int ID { get; set; }
public string State { get; set; }
// public DateTime? due { get; set; }
public int priorty { get; set; }
public int Size { get; set; }
// public int effort { get; set; }
public int StoryPoints { get; set; }
public string DoneStatus { get; set; }
public string StoryOwner { get; set; }
public string Assignedto { get; set; }
public string StoryAuthor { get; set; }
public string IterationPath { get; set; }
}
workitemlist image
rest of the code is pasted here
https://github.com/akhiljain1611/TFS/blob/master/README.md

You need to initialize the lists (Issues, Tasks and PBacklog) before you can begin adding items to it. I have done it using a constructor:
public class WorkItemViewModel
{
public int Id { get; set; }
public string Title { get; set; }
public string AssignedTo { get; set; }
public string WorkitemType { get; set; }
public string Priorty { get; set; }
public string IterationPath { get; set; }
public string State { get; set; }
public List<TFSIssue> Issues { get; set; }
public List<TFSTask> Tasks { get; set; }
public List<Backlogitem> PBacklog { get; set;}
public WorkItemViewModel() // Added a public constructor
{
Issues = new List<TFSIssue>();
Tasks = new List<TFSTask>();
PBacklog = new List<Backlogitem>();
}
}

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

App is freezing when trying to deserialize Json string to object

I'm not sure what is causing this to happen. When debugging, I can step through each line, but when it hits the DeserializeObject line, the program doesn't do anything. I can no longer step over or do anything else with the program. No error messages are being thrown either.
[Command("stats")]
public async Task LookupMonsterStats(CommandContext ctx, string name)
{
string monstersUri = "https://www.dnd5eapi.co/api/monsters/";
var formatted = name.Replace(" ", "-");
string apiResponse = string.Empty;
using (var httpClient = new HttpClient())
{
using (var response = await httpClient.GetAsync(monstersUri + formatted))
{
apiResponse = await response.Content.ReadAsStringAsync();
var monster = JsonConvert.DeserializeObject<Monster>(apiResponse);
}
}
await ctx.Channel.SendMessageAsync(apiResponse).ConfigureAwait(false);
}
Edit: Here is what my Monster class looks like
public class Monster
{
[JsonProperty("index")]
public string Index { get; set; }
[JsonProperty("name")]
public string Name{ get; set; }
[JsonProperty("size")]
public string Size { get; set; }
[JsonProperty("type")]
public string Type { get; set; }
[JsonProperty("subtype")]
public string Subtype { get; set; }
[JsonProperty("alignment")]
public string Alignment { get; set; }
[JsonProperty("armor_class")]
public int? ArmorClass { get; set; }
[JsonProperty("hit_points")]
public int? HitPoints { get; set; }
[JsonProperty("forms")]
public List<string> Forms { get; set; }
[JsonProperty("speed")]
public Object Speed { get; set; }
[JsonProperty("strength")]
public int? Strength { get; set; }
[JsonProperty("dexterity")]
public int? Dexterity { get; set; }
[JsonProperty("constitution")]
public int? Constitution { get; set; }
[JsonProperty("intelligence")]
public int? Intelligence { get; set; }
[JsonProperty("wisdom")]
public int? Wisdom { get; set; }
[JsonProperty("charisma")]
public int? Charisma { get; set; }
[JsonProperty("proficiencies")]
public List<string> Proficiencies { get; set; }
[JsonProperty("damage_vulnerabilities")]
public List<string> DamageVulnerabilities { get; set; }
[JsonProperty("damage_resistances")]
public List<string> DamageResistances { get; set; }
[JsonProperty("damage_immunities")]
public List<string> DamageImmunities { get; set; }
[JsonProperty("condition_immunities")]
public List<string> ConditionImmunities { get; set; }
[JsonProperty("senses")]
public Object Senses { get; set; }
[JsonProperty("languages")]
public string Languages { get; set; }
[JsonProperty("challenge_rating")]
public decimal? ChallengeRating { get; set; }
[JsonProperty("special_abilities")]
public List<string> SpecialAbilities { get; set; }
[JsonProperty("actions")]
public List<string> Actions { get; set; }
[JsonProperty("legendary_actions")]
public List<string> LegendaryActions { get; set; }
[JsonProperty("url")]
public string Url { get; set; }
}
As mentioned in a comment your class definition doesn't seem to match the JSON response, assuming you're using Visual Studio it's probably worth opening Debug / Windows / Exception Settings and make sure "Common Language Runtime Exceptions" is checked. Sometimes I've found stepping over in multi-threaded apps can produce unusual results after an exception.
When I pasted your code into LINQPad I got errors on several members you've defined as List<string> when the underlying type is more complex. What I normally do to avoid those errors is copy the raw json from a browser window to the clipboard and with a CS file open in Visual Studio do an Edit / Paste Special / Paste JSON as classes to automatically create the classes. After doing that I got the following that deserialized the data fine:
async Task Main()
{
await LookupMonsterStats("aboleth");
}
public async Task LookupMonsterStats(string name)
{
string monstersUri = "https://www.dnd5eapi.co/api/monsters/";
var formatted = name.Replace(" ", "-");
string apiResponse = string.Empty;
using (var httpClient = new HttpClient())
{
using (var response = await httpClient.GetAsync(monstersUri + formatted))
{
apiResponse = await response.Content.ReadAsStringAsync();
var monster = JsonConvert.DeserializeObject<Monster>(apiResponse);
monster.Dump();
}
}
}
public class Monster
{
public string index { get; set; }
public string name { get; set; }
public string size { get; set; }
public string type { get; set; }
public object subtype { get; set; }
public string alignment { get; set; }
public int armor_class { get; set; }
public int hit_points { get; set; }
public string hit_dice { get; set; }
public Speed speed { get; set; }
public int strength { get; set; }
public int dexterity { get; set; }
public int constitution { get; set; }
public int intelligence { get; set; }
public int wisdom { get; set; }
public int charisma { get; set; }
public Proficiency[] proficiencies { get; set; }
public object[] damage_vulnerabilities { get; set; }
public object[] damage_resistances { get; set; }
public object[] damage_immunities { get; set; }
public object[] condition_immunities { get; set; }
public Senses senses { get; set; }
public string languages { get; set; }
public int challenge_rating { get; set; }
public int xp { get; set; }
public Special_Abilities[] special_abilities { get; set; }
public Action[] actions { get; set; }
public Legendary_Actions[] legendary_actions { get; set; }
public string url { get; set; }
}
public class Speed
{
public string walk { get; set; }
public string swim { get; set; }
}
public class Senses
{
public string darkvision { get; set; }
public int passive_perception { get; set; }
}
public class Proficiency
{
public Proficiency1 proficiency { get; set; }
public int value { get; set; }
}
public class Proficiency1
{
public string index { get; set; }
public string name { get; set; }
public string url { get; set; }
}
public class Special_Abilities
{
public string name { get; set; }
public string desc { get; set; }
public Dc dc { get; set; }
}
public class Dc
{
public Dc_Type dc_type { get; set; }
public int dc_value { get; set; }
public string success_type { get; set; }
}
public class Dc_Type
{
public string index { get; set; }
public string name { get; set; }
public string url { get; set; }
}
public class Action
{
public string name { get; set; }
public string desc { get; set; }
public Options options { get; set; }
public Damage[] damage { get; set; }
public int attack_bonus { get; set; }
public Dc1 dc { get; set; }
public Usage usage { get; set; }
}
public class Options
{
public int choose { get; set; }
public From[][] from { get; set; }
}
public class From
{
public string name { get; set; }
public int count { get; set; }
public string type { get; set; }
}
public class Dc1
{
public Dc_Type1 dc_type { get; set; }
public int dc_value { get; set; }
public string success_type { get; set; }
}
public class Dc_Type1
{
public string index { get; set; }
public string name { get; set; }
public string url { get; set; }
}
public class Usage
{
public string type { get; set; }
public int times { get; set; }
}
public class Damage
{
public Damage_Type damage_type { get; set; }
public string damage_dice { get; set; }
}
public class Damage_Type
{
public string index { get; set; }
public string name { get; set; }
public string url { get; set; }
}
public class Legendary_Actions
{
public string name { get; set; }
public string desc { get; set; }
public int attack_bonus { get; set; }
public Damage1[] damage { get; set; }
}
public class Damage1
{
public Damage_Type1 damage_type { get; set; }
public string damage_dice { get; set; }
}
public class Damage_Type1
{
public string index { get; set; }
public string name { get; set; }
public string url { get; set; }
}

Json string deserialization C#

I have this json
and i want to deserialize it so I can get each object's value for example:
"icon_url": "-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgpouLWzKjhzw8zFdC5K092kl5SClMj3PLXFhGpC_Pp8j-3I4IG7i1Hn_UI-Nmj3ItDGe1BoN1mCr1G4xL_vhMS8tcmcn3JhuihwsHvbzQv3309k3tBw8A",
The problem is I can make the class(es) that I need so I can deserialize the json because the json string has nested objects.
I used json2csharp to help me generate classes. After some merging and cleaning up, this is what I got:
public class InventoryItem
{
public string id { get; set; }
public string classid { get; set; }
public string instanceid { get; set; }
public string amount { get; set; }
public int pos { get; set; }
}
public class AppData
{
public string def_index { get; set; }
public int? is_itemset_name { get; set; }
public int? limited { get; set; }
}
public class Description
{
public string type { get; set; }
public string value { get; set; }
public string color { get; set; }
public AppData app_data { get; set; }
}
public class Action
{
public string name { get; set; }
public string link { get; set; }
}
public class Tag
{
public string internal_name { get; set; }
public string name { get; set; }
public string category { get; set; }
public string category_name { get; set; }
public string color { get; set; }
}
public class RgDescription
{
public string appid { get; set; }
public string classid { get; set; }
public string instanceid { get; set; }
public string icon_url { get; set; }
public string icon_url_large { get; set; }
public string icon_drag_url { get; set; }
public string name { get; set; }
public string market_hash_name { get; set; }
public string market_name { get; set; }
public string name_color { get; set; }
public string background_color { get; set; }
public string type { get; set; }
public int tradable { get; set; }
public int marketable { get; set; }
public int commodity { get; set; }
public string market_tradable_restriction { get; set; }
public List<Description> descriptions { get; set; }
public List<Action> actions { get; set; }
public List<Action> market_actions { get; set; }
public List<Tag> tags { get; set; }
}
public class RootObject
{
public bool success { get; set; }
public IDictionary<string, InventoryItem> rgInventory { get; set; }
public List<object> rgCurrency { get; set; }
public IDictionary<string, RgDescription> rgDescriptions { get; set; }
public bool more { get; set; }
public bool more_start { get; set; }
}
These appear to work correctly, you can deserialize and serialize with code like this:
var obj = JsonConvert.DeserializeObject<RootObject>(oldString);
Console.WriteLine(obj.rgDescriptions["310776560_302028390"].icon_url); // e.g.
var newString = JsonConvert.SerializeObject(obj,
new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
// null value handling is optional, the above makes it a little more like the source string

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

C# Json Deserialization fails

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.

Categories