I am trying to save to the database the updated Account details object which contains a list of Player objects in it.
public class AccountDetails {
public String Id { get; set; }
public String Username { get; set; }
public String Email { get; set; }
public String Password { get; set; }
public String Token { get; set; }
public int PremiumDays { get; set; }
public List<Player> Players { get; set; }
public String LastLogin { get; set; }
public int AdminLevel { get; set; }
public int Banned { get; set; }
public int Muted { get; set; }
It seems to get this error on the Players part,
MongoDB.Bson.BsonSerializationException: 'Maximum serialization depth exceeded (does the object being serialized have a circular reference?).'
I have looked through the references for Player and the inherited GameObj but I cannot seem to find what might be causing this circular reference,
This is my Player Object,
public PlayerClass Class { get; set; }
public int Level { get; set; }
public string Name { get; set; }
public string Title { get; set; }
public List<Skill> Skills { get; set; }
public List<ArchewoodGameServer.core.Shared.Utils.Attribute> Attributes { get; set; }
public int AttributePoints { get; set; }
public int CurrentHealth { get; set; }
public int MaxHealth { get; set; }
public int CurrentMana { get; set; }
public int MaxMana { get; set; }
public int CurrentExp { get; set; }
public int MaxExp { get; set; }
[JsonIgnore]
public List<Node> Path = new List<Node>();
[JsonIgnore]
public int PathCount = 0;
[JsonIgnore]
public int HealthTick = 0, AttackTick = 10000, AnimTick = 0, MaxAnimTick = 20;
public float AttackSpeed { get; set; }
public ushort AttackRange { get; set; }
and this is my GameObj class,
public string Id { get; set; }
public float X { get; set; }
public float Y { get; set; }
public int O { get; set; }
public int A { get; set; }
public int T { get; set; }
public float S { get; set; }
[JsonIgnore]
public Instance Instance { get; set; }
[JsonIgnore]
public string InstanceID { get; set; }
[JsonIgnore]
public List<String> playerInteractions = new List<string>();
[JsonIgnore]
public int LastProcessedSequence { get; set; }
public string TargetEntity { get; set; }
public ushort PrivateId { get; set; }
The [JsonIgnore] were not working with mongos parser so I changed the structure to not rely on these tags and it was resolved.
I resolved problem in our core project on this way.
'
using Newtonsoft.Json;
using AutoMapper;
var stringContent = JsonConvert.SerializeObject(_mapper.Map<DataDTO>(newdata), new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }).ToString();
_mongoService.Save(JsonConvert.DeserializeObject<DataDTO>(stringContent));
//mongo service save method
public async void Save(DataDTO dataDTO)
{
await collection.InsertOneAsync(dataDTO));
}
'
Related
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;
}
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>();
}
}
I'm trying to deserialize some JSON code in a c# applicatie. I use the DataContractJsonSerializer class to do this. All works fine, until I get nested jsonobjects,
I recieve the following json from an external API:
[{"name":"Beeldscherm","json":"{\"onHomeEnter\":{\"state\":0,\"delay\":0,\"fadeTime\":0,\"active\":false,\"updatedAt\":1487166732440},\"onHomeExit\":{\"state\":0,\"delay\":120,\"fadeTime\":0,\"active\":false,\"updatedAt\":1487163669388},\"onRoomEnter\":{\"state\":1,\"delay\":0,\"fadeTime\":0,\"active\":false,\"updatedAt\":1},\"onRoomExit\":{\"state\":0,\"delay\":120,\"fadeTime\":0,\"active\":false,\"updatedAt\":1},\"onNear\":{\"state\":1,\"delay\":0,\"fadeTime\":0,\"active\":false,\"updatedAt\":1487164911729},\"onAway\":{\"state\":0,\"delay\":2,\"fadeTime\":0,\"active\":false,\"updatedAt\":1487164909184}}","id":"58a44fa04f40b016004ffca2","sphereId":"58a44c0a4f40b016004ffc9d","createdAt":"2017-02-15T13:52:12.783Z","updatedAt":"2017-02-15T12:55:05.332Z"}]
Which I edit with the following code:
responJsonText = responJsonText.Replace("\\", "").Replace("\"{", "{").Replace("}\"", "}");
and it then looks like this:
[{"name":"Beeldscherm","json":{"onHomeEnter":{"state":0,"delay":0,"fadeTime":0,"active":false,"updatedAt":1487166732440},"onHomeExit":{"state":0,"delay":120,"fadeTime":0,"active":false,"updatedAt":1487163669388},"onRoomEnter":{"state":1,"delay":0,"fadeTime":0,"active":false,"updatedAt":1},"onRoomExit":{"state":0,"delay":120,"fadeTime":0,"active":false,"updatedAt":1},"onNear":{"state":1,"delay":0,"fadeTime":0,"active":false,"updatedAt":1487164911729},"onAway":{"state":0,"delay":2,"fadeTime":0,"active":false,"updatedAt":1487164909184}},"id":"58a44fa04f40b016004ffca2","sphereId":"58a44c0a4f40b016004ffc9d","createdAt":"2017-02-15T13:52:12.783Z","updatedAt":"2017-02-15T12:55:05.332Z"}]
and try to parse this using the following classes:
[DataContract]
class Appliance
{
[DataMember]
public String name { get; set; }
[DataMember]
public ApplianceJson json { get; set; }
[DataMember]
public String id { get; set; }
[DataMember]
public String sphereId { get; set; }
[DataMember]
public String createdAt { get; set; }
[DataMember]
public String updatedAt { get; set; }
}
[DataContract]
class ApplianceJson
{
[DataMember]
public ApplianceEvents onHomeEnter { get; set; }
[DataMember]
public ApplianceEvents onHomeExit { get; set; }
[DataMember]
public ApplianceEvents onRoomEnter { get; set; }
[DataMember]
public ApplianceEvents onRoomExit { get; set; }
[DataMember]
public ApplianceEvents onNear { get; set; }
[DataMember]
public ApplianceEvents onAway { get; set; }
}
[DataContract]
class ApplianceEvents
{
[DataMember]
public int state { get; set; }
[DataMember]
public int delay { get; set; }
[DataMember]
public int fadeTime { get; set; }
[DataMember]
public bool active { get; set; }
[DataMember]
public int updatedAt { get; set; }
}
and the following code for the deserialization:
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(List<Appliance>));
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(responJsonText));
The error I get is:
Exception thrown: 'System.Runtime.Serialization.SerializationException' in System.Private.DataContractSerialization.dll
Exception thrown: 'System.Runtime.Serialization.SerializationException' in mscorlib.ni.dll
Does anybody see something that is wrong and how I could fix it?
Update
I checked the json string and its correct now, I've put the correct version in the question
Update 2
added the original JSON
if you notice the Original Json, You can see " is not \" but if you go deep into json, the Json Node itself has " as \". So i cleaned up all \" first and then again replaced " with \" Used Newtonsoft Json and then it parsed successfully. See my answer.
Using This Site and your JsonString, Below are the proper Json Class Structure that I created.
public class Appliance
{
public string name { get; set; }
public Json json { get; set; }
public string id { get; set; }
public string sphereId { get; set; }
public string createdAt { get; set; }
public string updatedAt { get; set; }
}
public class OnHomeEnter
{
public int state { get; set; }
public int delay { get; set; }
public int fadeTime { get; set; }
public bool active { get; set; }
public long updatedAt { get; set; }
}
public class OnHomeExit
{
public int state { get; set; }
public int delay { get; set; }
public int fadeTime { get; set; }
public bool active { get; set; }
public long updatedAt { get; set; }
}
public class OnRoomEnter
{
public int state { get; set; }
public int delay { get; set; }
public int fadeTime { get; set; }
public bool active { get; set; }
public int updatedAt { get; set; }
}
public class OnRoomExit
{
public int state { get; set; }
public int delay { get; set; }
public int fadeTime { get; set; }
public bool active { get; set; }
public int updatedAt { get; set; }
}
public class OnNear
{
public int state { get; set; }
public int delay { get; set; }
public int fadeTime { get; set; }
public bool active { get; set; }
public long updatedAt { get; set; }
}
public class OnAway
{
public int state { get; set; }
public int delay { get; set; }
public int fadeTime { get; set; }
public bool active { get; set; }
public long updatedAt { get; set; }
}
public class Json
{
public OnHomeEnter onHomeEnter { get; set; }
public OnHomeExit onHomeExit { get; set; }
public OnRoomEnter onRoomEnter { get; set; }
public OnRoomExit onRoomExit { get; set; }
public OnNear onNear { get; set; }
public OnAway onAway { get; set; }
}
Once Done, I used Json.Net
to Parse the JsonString to Appliance Object
Below is the Final Json String and Parser.
"[{\"name\":\"Beeldscherm\",\"json\":{\"onHomeEnter\":{\"state\":0,\"delay\":0,\"fadeTime\":0,\"active\":false,\"updatedAt\":1487166732440},\"onHomeExit\":{\"state\":0,\"delay\":120,\"fadeTime\":0,\"active\":false,\"updatedAt\":1487163669388},\"onRoomEnter\":{\"state\":1,\"delay\":0,\"fadeTime\":0,\"active\":false,\"updatedAt\":1},\"onRoomExit\":{\"state\":0,\"delay\":120,\"fadeTime\":0,\"active\":false,\"updatedAt\":1},\"onNear\":{\"state\":1,\"delay\":0,\"fadeTime\":0,\"active\":false,\"updatedAt\":1487164911729},\"onAway\":{\"state\":0,\"delay\":2,\"fadeTime\":0,\"active\":false,\"updatedAt\":1487164909184}},\"id\":\"58a44fa04f40b016004ffca2\",\"sphereId\":\"58a44c0a4f40b016004ffc9d\",\"createdAt\":\"2017 - 02 - 15T13: 52:12.783Z\",\"updatedAt\":\"2017 - 02 - 15T12: 55:05.332Z\"}]";
And Below is how I was able to successfully Parse Json.
List<Appliance> appJson = JsonConvert.DeserializeObject<List<Appliance>>(JsonData);
Good Luck.
I'm using Json.Net to DeserializeObject Json data into object/collection (list)
I'm not sure what I'm doing wrong and I have tried this:
public List<RootObject> GetRecipes()
{
string summonerID = Session["summonerID"].ToString();
string downloadedString;
WebClient client = new WebClient();
downloadedString = client.DownloadString("https://tr.api.pvp.net/api/lol/tr/v1.3/game/by-summoner/" + summonerID + "/recent?api_key=55686aef-da52-4184-b987-98799662d92e"); //tırnak içerisine istediğiniz web adresini yazınız
List<RootObject> liste = JsonConvert.DeserializeObject<List<RootObject>>(#downloadedString);
return liste;
lblYazi.Text = liste.ToString();
}
I'm getting this error:
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[KYLOL2.WebForm2+RootObject]' 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 'summonerId', line 1, position 14.
My Json link
My Class
public class FellowPlayer
{
public int summonerId { get; set; }
public int teamId { get; set; }
public int championId { get; set; }
}
public class Stats
{
public int level { get; set; }
public int goldEarned { get; set; }
public int numDeaths { get; set; }
public int minionsKilled { get; set; }
public int championsKilled { get; set; }
public int goldSpent { get; set; }
public int totalDamageDealt { get; set; }
public int totalDamageTaken { get; set; }
public int doubleKills { get; set; }
public int killingSprees { get; set; }
public int largestKillingSpree { get; set; }
public int team { get; set; }
public bool win { get; set; }
public int neutralMinionsKilled { get; set; }
public int largestMultiKill { get; set; }
public int physicalDamageDealtPlayer { get; set; }
public int magicDamageDealtPlayer { get; set; }
public int physicalDamageTaken { get; set; }
public int magicDamageTaken { get; set; }
public int largestCriticalStrike { get; set; }
public int timePlayed { get; set; }
public int totalHeal { get; set; }
public int totalUnitsHealed { get; set; }
public int assists { get; set; }
public int item0 { get; set; }
public int item1 { get; set; }
public int item2 { get; set; }
public int item3 { get; set; }
public int item4 { get; set; }
public int item6 { get; set; }
public int magicDamageDealtToChampions { get; set; }
public int physicalDamageDealtToChampions { get; set; }
public int totalDamageDealtToChampions { get; set; }
public int trueDamageTaken { get; set; }
public int neutralMinionsKilledEnemyJungle { get; set; }
public int totalTimeCrowdControlDealt { get; set; }
public int playerRole { get; set; }
public int playerPosition { get; set; }
public int? turretsKilled { get; set; }
public int? item5 { get; set; }
public int? wardPlaced { get; set; }
public int? neutralMinionsKilledYourJungle { get; set; }
public int? trueDamageDealtPlayer { get; set; }
public int? trueDamageDealtToChampions { get; set; }
public int? bountyLevel { get; set; }
public int? tripleKills { get; set; }
public int? wardKilled { get; set; }
public int? barracksKilled { get; set; }
}
public class Game
{
public int gameId { get; set; }
public bool invalid { get; set; }
public string gameMode { get; set; }
public string gameType { get; set; }
public string subType { get; set; }
public int mapId { get; set; }
public int teamId { get; set; }
public int championId { get; set; }
public int spell1 { get; set; }
public int spell2 { get; set; }
public int level { get; set; }
public int ipEarned { get; set; }
public object createDate { get; set; }
public List<FellowPlayer> fellowPlayers { get; set; }
public Stats stats { get; set; }
}
public class RootObject
{
public int summonerId { get; set; }
public List<Game> games { get; set; }
}
You are telling the deserializer to look for RootObject as a List, but it's not in the example you are providing. Something like this should work better:
RootObject liste = JsonConvert.DeserializeObject<RootObject>(#downloadedString);
So something like this:
public RootObject GetRecipes()
{
string summonerID = Session["summonerID"].ToString();
string downloadedString;
WebClient client = new WebClient();
downloadedString = client.DownloadString("https://tr.api.pvp.net/api/lol/tr/v1.3/game/by-summoner/" + summonerID + "/recent?api_key=55686aef-da52-4184-b987-98799662d92e"); //tırnak içerisine istediğiniz web adresini yazınız
RootObject liste = JsonConvert.DeserializeObject<RootObject>(#downloadedString);
return liste;
lblYazi.Text = liste.ToString(); // never reaches this code
}
or if you need to keep the prototype of the GetRecipes method:
public List<RootObject> GetRecipes()
{
string summonerID = Session["summonerID"].ToString();
string downloadedString;
WebClient client = new WebClient();
downloadedString = client.DownloadString("https://tr.api.pvp.net/api/lol/tr/v1.3/game/by-summoner/" + summonerID + "/recent?api_key=55686aef-da52-4184-b987-98799662d92e"); //tırnak içerisine istediğiniz web adresini yazınız
List<RootObject> liste = new List<RootObject>(); // create the return list
RootObject e = JsonConvert.DeserializeObject<RootObject>(#downloadedString);
liste.Add(e); // add the reserialized object to the list we are returning
return liste;
lblYazi.Text = liste.ToString(); // never reaches this code
}
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);