C# Reading json and edit - c#

SOLUTION
Profile newProfileList = new Profile();
newProfileList = myDeserializedClass.profiles[0]; // New profile list is null so i've casted some values from old ones.
myDeserializedClass.profiles.Add(newProfileList);
richTextBox1.Text = JsonConvert.SerializeObject(myDeserializedClass);
Then i can save it as json file again. Thanks to #Donut
I've got the following code:
OpenFileDialog ofd = new OpenFileDialog();
string txtProfile;
if (ofd.ShowDialog() == DialogResult.OK)
{
txtProfile = File.ReadAllText(ofd.FileName);
richTextBox1.Text = txtProfile;
}
Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(richTextBox1.Text);
Using this code, I'm able to read a JSON file and deserialize it successfully to an instance of the Root class. However, when I try to create new profiles in this object, I get some error about "read only values":
Form1.cs(124,13,124,47): error CS0200: Property or indexer 'List<Form1.Profile>.Count' cannot be assigned to -- it is read only
How can I correctly edit the deserialized data (e.g. add new instances of the Profile class), and save it back to the JSON file?
For reference, here are the classes I'm using for deserialization.
public class Metadata
{
public string app_flavor { get; set; }
public int app_version { get; set; }
}
public class Profile
{
public int ajax_connections_limit { get; set; }
public bool allow_emulator_ua_detection { get; set; }
public string apply_css_patches { get; set; }
public bool created_by_user { get; set; }
public string custom_user_agent { get; set; }
public bool device_custom_dev_id2 { get; set; }
public string device_id { get; set; }
public string device_id2 { get; set; }
public string device_id_seed { get; set; }
public string device_signature { get; set; }
public string display_resolution { get; set; }
public bool enable_ministra_compatibility { get; set; }
public bool external_player_send_back_key_event { get; set; }
public bool external_player_send_exit_key_event { get; set; }
public bool external_player_send_key_event { get; set; }
public bool external_player_send_ok_key_event { get; set; }
public string firmware { get; set; }
public string firmware_js_api_ver { get; set; }
public string firmware_player_engine_ver { get; set; }
public string firmware_stb_api_ver { get; set; }
public bool fix_ajax { get; set; }
public bool fix_background_color { get; set; }
public bool fix_local_file_scheme { get; set; }
public bool front_panel { get; set; }
public int generic_connections_limit { get; set; }
public string hardware_vendor { get; set; }
public string hardware_version { get; set; }
public string image_date { get; set; }
public string image_description { get; set; }
public string image_version { get; set; }
public string internal_portal_url { get; set; }
public bool is_internal_portal { get; set; }
public int lang_audiotracks { get; set; }
public int lang_subtitles { get; set; }
public string language { get; set; }
public bool limit_max_connections { get; set; }
public string mac_address { get; set; }
public string mac_seed_net_interface { get; set; }
public string media_player { get; set; }
public bool media_player_per_channel { get; set; }
public string name { get; set; }
public string ntp_server { get; set; }
public string overwrite_stream_protocol { get; set; }
public string playlist_charset { get; set; }
public string portal_url { get; set; }
public string proxy_host { get; set; }
public int proxy_port { get; set; }
public bool send_device_id { get; set; }
public string serial_number { get; set; }
public bool show_player_name { get; set; }
public string stb_internal_config { get; set; }
public string stb_model { get; set; }
public bool subtitles_on { get; set; }
public string tasks_data { get; set; }
public bool timeshift_enabled { get; set; }
public string timeshift_path { get; set; }
public string timezone { get; set; }
public bool udpxy_enabled { get; set; }
public string udpxy_url { get; set; }
public bool use_alt_stalker_auth_dialog { get; set; }
public bool use_alternative_web_view_scale_method { get; set; }
public bool use_browser_redirection { get; set; }
public bool use_custom_user_agent { get; set; }
public bool use_extended_mag_api { get; set; }
public bool use_http_proxy { get; set; }
public bool use_mac_based_device_id { get; set; }
public string user_agent { get; set; }
public string uuid { get; set; }
public string video_resolution { get; set; }
public int video_resume_time { get; set; }
public string weather_place { get; set; }
public bool web_proxy_enabled { get; set; }
}
public class Root
{
public Metadata metadata { get; set; }
public List<Profile> profiles { 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;
}

Name variable "private" [duplicate]

This question already has answers here:
C# keywords as a variable
(4 answers)
Use the long reserved word as a variable name in C#
(5 answers)
Closed 2 years ago.
I`m working on a project using .Net core, now I have Git hub's repository search api that I need to convert the data to c# object.
Using Json2Csharp (https://json2csharp.com/) I got that class:
public class Root {
public int id { get; set; }
public string node_id { get; set; }
public string name { get; set; }
public string full_name { get; set; }
public bool private { get; set; }
public Owner owner { get; set; }
public string html_url { get; set; }
public string description { get; set; }
public bool fork { get; set; }
public string url { get; set; }
public string forks_url { get; set; }
public string keys_url { get; set; }
public string collaborators_url { get; set; }
public string teams_url { get; set; }
public string hooks_url { get; set; }
public string issue_events_url { get; set; }
public string events_url { get; set; }
public string assignees_url { get; set; }
public string branches_url { get; set; }
public string tags_url { get; set; }
public string blobs_url { get; set; }
public string git_tags_url { get; set; }
public string git_refs_url { get; set; }
public string trees_url { get; set; }
public string statuses_url { get; set; }
public string languages_url { get; set; }
public string stargazers_url { get; set; }
public string contributors_url { get; set; }
public string subscribers_url { get; set; }
public string subscription_url { get; set; }
public string commits_url { get; set; }
public string git_commits_url { get; set; }
public string comments_url { get; set; }
public string issue_comment_url { get; set; }
public string contents_url { get; set; }
public string compare_url { get; set; }
public string merges_url { get; set; }
public string archive_url { get; set; }
public string downloads_url { get; set; }
public string issues_url { get; set; }
public string pulls_url { get; set; }
public string milestones_url { get; set; }
public string notifications_url { get; set; }
public string labels_url { get; set; }
public string releases_url { get; set; }
public string deployments_url { get; set; }
public DateTime created_at { get; set; }
public DateTime updated_at { get; set; }
public DateTime pushed_at { get; set; }
public string git_url { get; set; }
public string ssh_url { get; set; }
public string clone_url { get; set; }
public string svn_url { get; set; }
public string homepage { get; set; }
public int size { get; set; }
public int stargazers_count { get; set; }
public int watchers_count { get; set; }
public string language { get; set; }
public bool has_issues { get; set; }
public bool has_projects { get; set; }
public bool has_downloads { get; set; }
public bool has_wiki { get; set; }
public bool has_pages { get; set; }
public int forks_count { get; set; }
public object mirror_url { get; set; }
public bool archived { get; set; }
public bool disabled { get; set; }
public int open_issues_count { get; set; }
public License license { get; set; }
public int forks { get; set; }
public int open_issues { get; set; }
public int watchers { get; set; }
public string default_branch { get; set; }
public double score { get; set; }
}
As you see there is a bool variable called 'private' and it keeps compile error
Member modifier 'private' must precede the member type and name
My question is can I override the 'private' name or ignore the compiler error somehow?
You have to use JsonPropertyAttribute
[JsonProperty("private")]
public string whatever{get;set;} //you can give any name, it will be translated as "private"

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

Error parsing JSON with NewtonSoft

Merry Christmas stackies! I'm trying to parse some JSON from the Wunderground weather API and I'm running into an issue when trying to assign values to variables. Here is a link to the JSON. Just know that the class structure I'm providing is a conglomerate in order to accommodate multiple JSON return file structures. I'll give the class structre, then the call from main, and finally the actual method with the error notated. I'm working in Xamarin, formerlly MonoDevelop. Thanks for anything you can come up with!
The error reads:
Newtonsoft.Json.JsonReaderException has been thrown
"Cannot convert String to Integer: 5.0 Path
'current_observation.wind_gust_mph', line 60, position 24.
public class Wunder
{
//constructor
public Wunder ()
{
}
//JSON classes
public class HistoryResponseContainer
{
public ResponseInfo response { get; set; }
public HistoryInfo history { get; set; }
public Location location { get; set; }
public CurrentObservation current_observation { get; set; }
}
public class ResponseInfo
{
public string version { get; set; }
public string termsofService { get; set; }
public Dictionary<string, int> features { get; set; }
}
public class HistoryInfo
{
public WUDate date { get; set; }
public WUDate utcdate { get; set; }
public Observation[] observations { get; set; }
public Dailysummary[] dailysummary { get; set; }
}
public class WUDate
{
public string pretty { get; set; }
public string year { get; set; }
public string mon { get; set; }
public string mday { get; set; }
public string hour { get; set; }
public string min { get; set; }
public string tzname { get; set; }
public DateTime Value
{
get
{
int year = int.Parse(this.year);
int month = int.Parse(this.mon);
int day = int.Parse(this.mday);
int hour = int.Parse(this.hour);
int minute = int.Parse(this.min);
var kind = this.tzname == "UTC"
? DateTimeKind.Utc
: DateTimeKind.Unspecified;
return new DateTime(year, month, day, hour, minute, 0, kind);
}
}
}
public class Observation
{
public WUDate date { get; set; }
public WUDate utcdate { get; set; }
public string tempm { get; set; }
public string tempi { get; set; }
public string dewptm { get; set; }
public string dewpti { get; set; }
public string hum { get; set; }
public string wspdm { get; set; }
public string wspdi { get; set; }
public string wgustm { get; set; }
public string wgusti { get; set; }
public string wdird { get; set; }
public string wdire { get; set; }
public string vism { get; set; }
public string visi { get; set; }
public string pressurem { get; set; }
public string pressurei { get; set; }
public string windchillm { get; set; }
public string windchilli { get; set; }
public string heatindexm { get; set; }
public string heatindexi { get; set; }
public string precipm { get; set; }
public string precipi { get; set; }
public string conds { get; set; }
public string icon { get; set; }
public string fog { get; set; }
public string rain { get; set; }
public string snow { get; set; }
public string hail { get; set; }
public string thunder { get; set; }
public string tornado { get; set; }
public string metar { get; set; }
}
public class Dailysummary
{
public WUDate date { get; set; }
public string fog { get; set; }
public string rain { get; set; }
public string snow { get; set; }
public string snowfallm { get; set; }
public string snowfalli { get; set; }
public string monthtodatesnowfallm { get; set; }
public string monthtodatesnowfalli { get; set; }
public string since1julsnowfallm { get; set; }
public string since1julsnowfalli { get; set; }
public string snowdepthm { get; set; }
public string snowdepthi { get; set; }
public string hail { get; set; }
public string thunder { get; set; }
public string tornado { get; set; }
public string meantempm { get; set; }
public string meantempi { get; set; }
public string meandewptm { get; set; }
public string meandewpti { get; set; }
public string meanpressurem { get; set; }
public string meanpressurei { get; set; }
public string meanwindspdm { get; set; }
public string meanwindspdi { get; set; }
public string meanwdire { get; set; }
public string meanwdird { get; set; }
public string meanvism { get; set; }
public string meanvisi { get; set; }
public string humidity { get; set; }
public string maxtempm { get; set; }
public string maxtempi { get; set; }
public string mintempm { get; set; }
public string mintempi { get; set; }
public string maxhumidity { get; set; }
public string minhumidity { get; set; }
public string maxdewptm { get; set; }
public string maxdewpti { get; set; }
public string mindewptm { get; set; }
public string mindewpti { get; set; }
public string maxpressurem { get; set; }
public string maxpressurei { get; set; }
public string minpressurem { get; set; }
public string minpressurei { get; set; }
public string maxwspdm { get; set; }
public string maxwspdi { get; set; }
public string minwspdm { get; set; }
public string minwspdi { get; set; }
public string maxvism { get; set; }
public string maxvisi { get; set; }
public string minvism { get; set; }
public string minvisi { get; set; }
public string gdegreedays { get; set; }
public string heatingdegreedays { get; set; }
public string coolingdegreedays { get; set; }
public string precipm { get; set; }
public string precipi { get; set; }
public string precipsource { get; set; }
public string heatingdegreedaysnormal { get; set; }
public string monthtodateheatingdegreedays { get; set; }
public string monthtodateheatingdegreedaysnormal { get; set; }
public string since1sepheatingdegreedays { get; set; }
public string since1sepheatingdegreedaysnormal { get; set; }
public string since1julheatingdegreedays { get; set; }
public string since1julheatingdegreedaysnormal { get; set; }
public string coolingdegreedaysnormal { get; set; }
public string monthtodatecoolingdegreedays { get; set; }
public string monthtodatecoolingdegreedaysnormal { get; set; }
public string since1sepcoolingdegreedays { get; set; }
public string since1sepcoolingdegreedaysnormal { get; set; }
public string since1jancoolingdegreedays { get; set; }
public string since1jancoolingdegreedaysnormal { get; set; }
}
public class Station
{
public string city { get; set; }
public string state { get; set; }
public string country { get; set; }
public string icao { get; set; }
public string lat { get; set; }
public string lon { get; set; }
}
public class Airport
{
public List<Station> station { get; set; }
}
public class Station2
{
public string neighborhood { get; set; }
public string city { get; set; }
public string state { get; set; }
public string country { get; set; }
public string id { get; set; }
public double lat { get; set; }
public double lon { get; set; }
public int distance_km { get; set; }
public int distance_mi { get; set; }
}
public class Pws
{
public List<Station2> station { get; set; }
}
public class NearbyWeatherStations
{
public Airport airport { get; set; }
public Pws pws { get; set; }
}
public class Location
{
public string type { get; set; }
public string country { get; set; }
public string country_iso3166 { get; set; }
public string country_name { get; set; }
public string state { get; set; }
public string city { get; set; }
public string tz_short { get; set; }
public string tz_long { get; set; }
public string lat { get; set; }
public string lon { get; set; }
public string zip { get; set; }
public string magic { get; set; }
public string wmo { get; set; }
public string l { get; set; }
public string requesturl { get; set; }
public string wuiurl { get; set; }
public NearbyWeatherStations nearby_weather_stations { get; set; }
}
public class CurrentObservation
{
public Image image { get; set; }
public DisplayLocation display_location { get; set; }
public ObservationLocation observation_location { get; set; }
public Estimated estimated { get; set; }
public string station_id { get; set; }
public string observation_time { get; set; }
public string observation_time_rfc822 { get; set; }
public string observation_epoch { get; set; }
public string local_time_rfc822 { get; set; }
public string local_epoch { get; set; }
public string local_tz_short { get; set; }
public string local_tz_long { get; set; }
public string local_tz_offset { get; set; }
public string weather { get; set; }
public string temperature_string { get; set; }
public double temp_f { get; set; }
public double temp_c { get; set; }
public string relative_humidity { get; set; }
public string wind_string { get; set; }
public string wind_dir { get; set; }
public int wind_degrees { get; set; }
public double wind_mph { get; set; }
public int wind_gust_mph { get; set; }
public int wind_kph { get; set; }
public int wind_gust_kph { get; set; }
public string pressure_mb { get; set; }
public string pressure_in { get; set; }
public string pressure_trend { get; set; }
public string dewpoint_string { get; set; }
public int dewpoint_f { get; set; }
public int dewpoint_c { get; set; }
public string heat_index_string { get; set; }
public string heat_index_f { get; set; }
public string heat_index_c { get; set; }
public string windchill_string { get; set; }
public string windchill_f { get; set; }
public string windchill_c { get; set; }
public string feelslike_string { get; set; }
public string feelslike_f { get; set; }
public string feelslike_c { get; set; }
public string visibility_mi { get; set; }
public string visibility_km { get; set; }
public string solarradiation { get; set; }
public string UV { get; set; }
public string precip_1hr_string { get; set; }
public string precip_1hr_in { get; set; }
public string precip_1hr_metric { get; set; }
public string precip_today_string { get; set; }
public string precip_today_in { get; set; }
public string precip_today_metric { get; set; }
public string icon { get; set; }
public string icon_url { get; set; }
public string forecast_url { get; set; }
public string history_url { get; set; }
public string ob_url { get; set; }
}
public class ObservationLocation
{
public string full { get; set; }
public string city { get; set; }
public string state { get; set; }
public string country { get; set; }
public string country_iso3166 { get; set; }
public string latitude { get; set; }
public string longitude { get; set; }
public string elevation { get; set; }
}
public class Image
{
public string url { get; set; }
public string title { get; set; }
public string link { get; set; }
}
public class DisplayLocation
{
public string full { get; set; }
public string city { get; set; }
public string state { get; set; }
public string state_name { get; set; }
public string country { get; set; }
public string country_iso3166 { get; set; }
public string zip { get; set; }
public string magic { get; set; }
public string wmo { get; set; }
public string latitude { get; set; }
public string longitude { get; set; }
public string elevation { get; set; }
}
public class Estimated
{
}
And here is the call from main.
class MainClass
{
public static void Main (string[] args)
{
Wunder data = new Wunder ();
string StationID = "KCOBOULD67";
string CurrentConditions = data.GetCurrentConditions (StationID);
Console.WriteLine (CurrentConditions);
}
}
Lastly, this is the method being called. I took out my Wunderground Key. If you want an example of the return JSON, check the link at the top.
public String GetCurrentConditions(string StationID){
String url = #"http://api.wunderground.com/api/" + wundergroundkey + "/conditions/q/pws:" + StationID + ".json";
Uri uri = new Uri(url);
WebRequest webRequest = WebRequest.Create(uri);
WebResponse response = webRequest.GetResponse();
StreamReader streamReader = new StreamReader(response.GetResponseStream());
String responseData = streamReader.ReadToEnd();
var container = JsonConvert.DeserializeObject<HistoryResponseContainer> (responseData);
String stationid = container.current_observation.station_id;
String station_lat = container.current_observation.observation_location.latitude;
String station_lon = container.current_observation.observation_location.longitude;
String station_data = stationid + station_lat + station_lon;
return (station_data);
} //End GetCurrentConditions
Again, the error reads:
Newtonsoft.Json.JsonReaderException has been thrown
"Cannot convert String to Integer: 5.0 Path
'current_observation.wind_gust_mph', line 60, position 24.
You provided us a link to the following JSON:
http://api.wunderground.com/api/21fd5aec70326254/conditions/q/CA/San_Francisco.json
As you see there, the property wind_gust_mph is 0 (without the quotes, so an Integer). This JSON also works very well. But in your code you use the following JSON:
http://api.wunderground.com/api/21fd5aec70326254/conditions/q/pws:KCOBOULD67.json
And there the property wind_gust_mph is "4.0" (with the quotes, so a String). And you cannot parse a string property into an integer. Also the properties for wind_kph and wind_gust_kph are wrong, this should be either string or double:
public string wind_gust_mph { get; set; }
public double wind_kph { get; set; }
public string wind_gust_kph { get; set; }
Hope this helps and merry x-mas.

Categories