RestSharp Post Request with serialized JSON object - c#

I am trying to post a serialized object using RestSharp object is :
public class WebCRMOrganisation : IWebCRMOrganisation
{
[JsonProperty("OrganisationAddress")]
public string OrganisationAddress { get; set; }
[JsonProperty("OrganisationAlert")]
public string OrganisationAlert { get; set; }
[JsonProperty("OrganisationApprovalStatus")]
public long OrganisationApprovalStatus { get; set; }
[JsonProperty("OrganisationCity")]
public string OrganisationCity { get; set; }
[JsonProperty("OrganisationComment")]
public string OrganisationComment { get; set; }
[JsonProperty("OrganisationCompareName")]
public string OrganisationCompareName { get; set; }
[JsonProperty("OrganisationCountry")]
public string OrganisationCountry { get; set; }
[JsonProperty("OrganisationCreatedAt")]
public System.DateTimeOffset OrganisationCreatedAt { get; set; }
[JsonProperty("OrganisationCreatedBy")]
public string OrganisationCreatedBy { get; set; }
[JsonProperty("OrganisationDivisionName")]
public string OrganisationDivisionName { get; set; }
[JsonProperty("OrganisationDomain")]
public string OrganisationDomain { get; set; }
[JsonProperty("OrganisationExtraCustom1")]
public string OrganisationExtraCustom1 { get; set; }
[JsonProperty("OrganisationExtraCustom2")]
public string OrganisationExtraCustom2 { get; set; }
[JsonProperty("OrganisationExtraCustom3")]
public string OrganisationExtraCustom3 { get; set; }
[JsonProperty("OrganisationExtraCustom4")]
public string OrganisationExtraCustom4 { get; set; }
[JsonProperty("OrganisationExtraCustom5")]
public string OrganisationExtraCustom5 { get; set; }
[JsonProperty("OrganisationExtraCustom6")]
public string OrganisationExtraCustom6 { get; set; }
[JsonProperty("OrganisationExtraCustom7")]
public string OrganisationExtraCustom7 { get; set; }
[JsonProperty("OrganisationExtraCustom8")]
public string OrganisationExtraCustom8 { get; set; }
[JsonProperty("OrganisationFax")]
public string OrganisationFax { get; set; }
[JsonProperty("OrganisationGps")]
public string OrganisationGps { get; set; }
[JsonProperty("OrganisationId")]
public long OrganisationId { get; set; }
[JsonProperty("OrganisationImageFileExtension")]
public string OrganisationImageFileExtension { get; set; }
[JsonProperty("OrganisationIndustry")]
public string OrganisationIndustry { get; set; }
[JsonProperty("OrganisationLastDisplayedAt")]
public System.DateTimeOffset OrganisationLastDisplayedAt { get; set; }
[JsonProperty("OrganisationLastItemType")]
public string OrganisationLastItemType { get; set; }
[JsonProperty("OrganisationLastItemUpdatedAt")]
public System.DateTimeOffset OrganisationLastItemUpdatedAt { get; set; }
[JsonProperty("OrganisationMarketDataId")]
public string OrganisationMarketDataId { get; set; }
[JsonProperty("OrganisationName")]
public string OrganisationName { get; set; }
[JsonProperty("OrganisationNoAds")]
public bool OrganisationNoAds { get; set; }
[JsonProperty("OrganisationHistory")]
public string OrganisationHistory { get; set; }
[JsonProperty("OrganisationOutlookSync")]
public long OrganisationOutlookSync { get; set; }
[JsonProperty("OrganisationOverlayUrl")]
public string OrganisationOverlayUrl { get; set; }
[JsonProperty("OrganisationOwner")]
public long OrganisationOwner { get; set; }
[JsonProperty("OrganisationOwner2")]
public long OrganisationOwner2 { get; set; }
[JsonProperty("OrganisationPostCode")]
public string OrganisationPostCode { get; set; }
[JsonProperty("OrganisationReportTemp")]
public long OrganisationReportTemp { get; set; }
[JsonProperty("OrganisationSla")]
public long OrganisationSla { get; set; }
[JsonProperty("OrganisationState")]
public string OrganisationState { get; set; }
[JsonProperty("OrganisationStatus")]
public string OrganisationStatus { get; set; }
[JsonProperty("OrganisationTelephone")]
public string OrganisationTelephone { get; set; }
[JsonProperty("OrganisationTelephoneSearch")]
public string OrganisationTelephoneSearch { get; set; }
[JsonProperty("OrganisationTerritoryId")]
public long OrganisationTerritoryId { get; set; }
[JsonProperty("OrganisationType")]
public string OrganisationType { get; set; }
[JsonProperty("OrganisationUpdatedAt")]
public System.DateTimeOffset OrganisationUpdatedAt { get; set; }
[JsonProperty("OrganisationUpdatedBy")]
public string OrganisationUpdatedBy { get; set; }
[JsonProperty("OrganisationVatCountry")]
public string OrganisationVatCountry { get; set; }
[JsonProperty("OrganisationVatGroup")]
public string OrganisationVatGroup { get; set; }
[JsonProperty("OrganisationVatNumber")]
public string OrganisationVatNumber { get; set; }
[JsonProperty("OrganisationVatStatus")]
public string OrganisationVatStatus { get; set; }
[JsonProperty("OrganisationVatVerifiedAt")]
public System.DateTimeOffset OrganisationVatVerifiedAt { get; set; }
[JsonProperty("OrganisationWww")]
public string OrganisationWww { get; set; }
[JsonProperty("OrganisationXDate1")]
public System.DateTimeOffset OrganisationXDate1 { get; set; }
[JsonProperty("OrganisationXDate2")]
public System.DateTimeOffset OrganisationXDate2 { get; set; }
[JsonProperty("OrganisationXInt1")]
public long OrganisationXInt1 { get; set; }
[JsonProperty("OrganisationXInt2")]
public long OrganisationXInt2 { get; set; }
[JsonProperty("OrganisationXInt3")]
public long OrganisationXInt3 { get; set; }
[JsonProperty("OrganisationXInt4")]
public long OrganisationXInt4 { get; set; }
[JsonProperty("OrganisationXInt5")]
public long OrganisationXInt5 { get; set; }
[JsonProperty("OrganisationXInt6")]
public long OrganisationXInt6 { get; set; }
[JsonProperty("OrganisationXInt7")]
public long OrganisationXInt7 { get; set; }
[JsonProperty("OrganisationXInt8")]
public long OrganisationXInt8 { get; set; }
[JsonProperty("OrganisationXMemo1")]
public string OrganisationXMemo1 { get; set; }
[JsonProperty("OrganisationXMemo2")]
public string OrganisationXMemo2 { get; set; }
[JsonProperty("OrganisationXText1")]
public string OrganisationXText1 { get; set; }
[JsonProperty("OrganisationXText2")]
public string OrganisationXText2 { get; set; }
[JsonProperty("OrganisationXText3")]
public string OrganisationXText3 { get; set; }
[JsonProperty("OrganisationXText4")]
public string OrganisationXText4 { get; set; }
[JsonProperty("OrganisationXText5")]
public string OrganisationXText5 { get; set; }
[JsonProperty("OrganisationXText6")]
public string OrganisationXText6 { get; set; }
[JsonProperty("OrganisationXText7")]
public string OrganisationXText7 { get; set; }
[JsonProperty("OrganisationXText8")]
public string OrganisationXText8 { get; set; }
[JsonProperty("OrganisationPlus1")]
public string OrganisationPlus1 { get; set; }
[JsonProperty("OrganisationPlus2")]
public string OrganisationPlus2 { get; set; }
[JsonProperty("OrganisationPlus3")]
public string OrganisationPlus3 { get; set; }
[JsonProperty("OrganisationPlus4")]
public string OrganisationPlus4 { get; set; }
[JsonProperty("OrganisationPlus5")]
public string OrganisationPlus5 { get; set; }
[JsonProperty("OrganisationPlus6")]
public string OrganisationPlus6 { get; set; }
[JsonProperty("OrganisationPlus7")]
public string OrganisationPlus7 { get; set; }
[JsonProperty("OrganisationPlus8")]
public string OrganisationPlus8 { get; set; }
[JsonProperty("OrganisationPlus9")]
public string OrganisationPlus9 { get; set; }
[JsonProperty("OrganisationPlus10")]
public string OrganisationPlus10 { get; set; }
[JsonProperty("OrganisationPlus11")]
public string OrganisationPlus11 { get; set; }
[JsonProperty("OrganisationPlus12")]
public string OrganisationPlus12 { get; set; }
[JsonProperty("OrganisationPlus13")]
public string OrganisationPlus13 { get; set; }
[JsonProperty("OrganisationPlus14")]
public string OrganisationPlus14 { get; set; }
[JsonProperty("OrganisationPlus15")]
public string OrganisationPlus15 { get; set; }
[JsonProperty("OrganisationPlus16")]
public string OrganisationPlus16 { get; set; }
[JsonProperty("OrganisationPlus17")]
public string OrganisationPlus17 { get; set; }
[JsonProperty("OrganisationPlus18")]
public string OrganisationPlus18 { get; set; }
[JsonProperty("OrganisationPlus19")]
public string OrganisationPlus19 { get; set; }
[JsonProperty("OrganisationPlus20")]
public string OrganisationPlus20 { get; set; }
[JsonProperty("OrganisationCustom1")]
public string OrganisationCustom1 { get; set; }
[JsonProperty("OrganisationCustom2")]
public string OrganisationCustom2 { get; set; }
[JsonProperty("OrganisationCustom3")]
public string OrganisationCustom3 { get; set; }
[JsonProperty("OrganisationCustom4")]
public string OrganisationCustom4 { get; set; }
[JsonProperty("OrganisationCustom5")]
public string OrganisationCustom5 { get; set; }
[JsonProperty("OrganisationCustom6")]
public string OrganisationCustom6 { get; set; }
[JsonProperty("OrganisationCustom7")]
public string OrganisationCustom7 { get; set; }
[JsonProperty("OrganisationCustom8")]
public string OrganisationCustom8 { get; set; }
[JsonProperty("OrganisationCustom9")]
public string OrganisationCustom9 { get; set; }
[JsonProperty("OrganisationCustom10")]
public string OrganisationCustom10 { get; set; }
[JsonProperty("OrganisationCustom11")]
public string OrganisationCustom11 { get; set; }
[JsonProperty("OrganisationCustom12")]
public string OrganisationCustom12 { get; set; }
[JsonProperty("OrganisationCustom13")]
public string OrganisationCustom13 { get; set; }
[JsonProperty("OrganisationCustom14")]
public string OrganisationCustom14 { get; set; }
[JsonProperty("OrganisationCustom15")]
public string OrganisationCustom15 { get; set; }
[JsonProperty("OrganisationMemo")]
public string OrganisationMemo { get; set; }
}
I have tried the following code but every time I am getting bad request in response, I have checked API reference documentation JSON format is correct and I have also tried API's swagger reference I am able to use their methods fine.
var client = new RestClient("https://api.webcrm.com");
var request = new RestRequest("Organisations", Method.POST);
request.AddHeader("Accept", "application/json");
request.AddHeader("Content-Type", "application/json");
request.RequestFormat = DataFormat.Json;
request.AddParameter("application/json", JsonConvert.SerializeObject(organisation),
ParameterType.RequestBody);
WebCRMConnectivityResult c = CheckConnectivity();
request.AddHeader("Authorization", string.Format("Bearer {0}",c.AccessToken));
//request.RootElement = "organisation";
IRestResponse response = client.Execute(request);
var content = response.Content;
Can anyone please tell me what could be the issue?

Related

C# Reading json and edit

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

Given json as a response but not sure how to parse it

I am using this code to attempt to parse my response back from the payment gateway:
var responseMessage = client.PostAsJsonAsync("transaction", transData).Result;
var response = responseMessage.Content.ReadAsStringAsync().Result;
MessageBox.Show(response);
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
var objCustomer = jsonSerializer.Deserialize<ReturnValues.RootObject>(response);
This is the class I am trying to create:
public class ReturnValues
{
public class Card
{
public string id { get; set; }
public string card_type { get; set; }
public string first_six { get; set; }
public string last_four { get; set; }
public string masked_card { get; set; }
public string expiration_date { get; set; }
public string status { get; set; }
public string auth_code { get; set; }
public string processor_response_code { get; set; }
public string processor_response_text { get; set; }
public string processor_type { get; set; }
public string processor_id { get; set; }
public string avs_response_code { get; set; }
public string cvv_response_code { get; set; }
public DateTime created_at { get; set; }
public DateTime updated_at { get; set; }
}
public class Response
{
public Card card { get; set; }
}
public class BillingAddress
{
public string first_name { get; set; }
public string last_name { get; set; }
public string company { get; set; }
public string address_line_1 { get; set; }
public string address_line_2 { get; set; }
public string city { get; set; }
public string state { get; set; }
public string postal_code { get; set; }
public string country { get; set; }
public string phone { get; set; }
public string fax { get; set; }
public string email { get; set; }
}
public class ShippingAddress
{
public string first_name { get; set; }
public string last_name { get; set; }
public string company { get; set; }
public string address_line_1 { get; set; }
public string address_line_2 { get; set; }
public string city { get; set; }
public string state { get; set; }
public string postal_code { get; set; }
public string country { get; set; }
public string phone { get; set; }
public string fax { get; set; }
public string email { get; set; }
}
public class Data
{
public string id { get; set; }
public string type { get; set; }
public int amount { get; set; }
public int tax_amount { get; set; }
public bool tax_exempt { get; set; }
public int shipping_amount { get; set; }
public int discount_amount { get; set; }
public string payment_adjustment_type { get; set; }
public int payment_adjustment_value { get; set; }
public string currency { get; set; }
public string description { get; set; }
public string order_id { get; set; }
public string po_number { get; set; }
public string ip_address { get; set; }
public bool email_receipt { get; set; }
public string email_address { get; set; }
public string payment_method { get; set; }
public Response response { get; set; }
public string status { get; set; }
public int response_code { get; set; }
public string customer_id { get; set; }
public BillingAddress billing_address { get; set; }
public ShippingAddress shipping_address { get; set; }
public DateTime created_at { get; set; }
public DateTime updated_at { get; set; }
}
public class RootObject
{
public string status { get; set; }
public string msg { get; set; }
public Data data { get; set; }
}
}
This is the response I am given:
"{\"status\":\"success\",\"msg\":\"success\",\"data\":{\"id\":\"bp2pa41erttupu3q1eng\",\"user_id\":\"bmibms9erttqdc2kigl0\",\"user_name\":\"dev\",\"merchant_id\":\"asdfasdf\",\"idempotency_key\":\"\",\"idempotency_time\":0,\"type\":\"sale\",\"amount\":1000,\"base_amount\":1000,\"amount_authorized\":1000,\"amount_captured\":1000,\"amount_settled\":0,\"amount_refunded\":0,\"payment_adjustment\":0,\"tip_amount\":0,\"settlement_batch_id\":\"\",\"processor_id\":\"bmibnfperttqdc2kigmg\",\"processor_type\":\"tsys_sierra\",\"processor_name\":\"Keyed
Credit
Cards\",\"payment_method\":\"card\",\"payment_type\":\"card\",\"features\":[\"avs\",\"card_verification\",\"levelii\",\"fake_response\"],\"national_tax_amount\":0,\"duty_amount\":0,\"ship_from_postal_code\":\"\",\"summary_commodity_code\":\"\",\"merchant_vat_registration_number\":\"\",\"customer_vat_registration_number\":\"\",\"tax_amount\":0,\"tax_exempt\":false,\"shipping_amount\":0,\"surcharge\":0,\"discount_amount\":0,\"currency\":\"usd\",\"description\":\"This
is a
test\",\"order_id\":\"555555\",\"po_number\":\"666666\",\"ip_address\":\"1.1.1.1\",\"transaction_source\":\"api\",\"email_receipt\":false,\"email_address\":\"\",\"customer_id\":\"\",\"customer_payment_type\":\"\",\"customer_payment_ID\":\"\",\"subscription_id\":\"\",\"referenced_transaction_id\":\"\",\"response_body\":{\"card\":{\"id\":\"bp2pa41erttupu3q1eo0\",\"card_type\":\"visa\",\"first_six\":\"401288\",\"last_four\":\"1881\",\"masked_card\":\"401288******1881\",\"expiration_date\":\"12/21\",\"response\":\"approved\",\"response_code\":100,\"auth_code\":\"TAS000\",\"processor_response_code\":\"00\",\"processor_response_text\":\"APPROVAL
TAS000
\",\"processor_transaction_id\":\"000000000000000\",\"processor_type\":\"tsys_sierra\",\"processor_id\":\"bmgwgtgtherhemg\",\"avs_response_code\":\"M\",\"cvv_response_code\":\"M\",\"processor_specific\":null,\"created_at\":\"2020-02-13T18:27:28.149933095Z\",\"updated_at\":\"2020-02-13T18:27:28.196367669Z\"}},\"custom_fields\":{},\"line_items\":null,\"status\":\"pending_settlement\",\"response\":\"approved\",\"response_code\":100,\"billing_address\":{\"first_name\":\"John\",\"last_name\":\"Doe\",\"company\":\"\",\"address_line_1\":\"123
Some
Street\",\"address_line_2\":\"\",\"city\":\"Bessemer\",\"state\":\"AL\",\"postal_code\":\"35020\",\"country\":\"US\",\"phone\":\"5555555555\",\"fax\":\"\",\"email\":\"test#gmail.com\"},\"shipping_address\":{\"first_name\":\"\",\"last_name\":\"\",\"company\":\"\",\"address_line_1\":\"\",\"address_line_2\":\"\",\"city\":\"\",\"state\":\"\",\"postal_code\":\"\",\"country\":\"\",\"phone\":\"\",\"fax\":\"\",\"email\":\"\"},\"created_at\":\"2020-02-13T18:27:28.104845544Z\",\"updated_at\":\"2020-02-13T18:27:28.200963331Z\",\"captured_at\":\"2020-02-13T18:27:28.200962679Z\",\"settled_at\":null}}\n"
I am getting this message:
System.InvalidOperationException: 'Cannot convert object of type
'System.String' to type 'Test.ReturnValues+Response''
I am not sure what I am doing wrong. I used an online json converter to get my class. It appears to be correct.
Any suggestions?
I used json2csharp.com to generate C# classes and it came up with something different.
public class ReturnValues
{
public class Card
{
public string id { get; set; }
public string card_type { get; set; }
public string first_six { get; set; }
public string last_four { get; set; }
public string masked_card { get; set; }
public string expiration_date { get; set; }
public string response { get; set; }
public int response_code { get; set; }
public string auth_code { get; set; }
public string processor_response_code { get; set; }
public string processor_response_text { get; set; }
public string processor_transaction_id { get; set; }
public string processor_type { get; set; }
public string processor_id { get; set; }
public string avs_response_code { get; set; }
public string cvv_response_code { get; set; }
public object processor_specific { get; set; }
public string created_at { get; set; }
public string updated_at { get; set; }
}
public class ResponseBody
{
public Card card { get; set; }
}
public class CustomFields
{
}
public class BillingAddress
{
public string first_name { get; set; }
public string last_name { get; set; }
public string company { get; set; }
public string address_line_1 { get; set; }
public string address_line_2 { get; set; }
public string city { get; set; }
public string state { get; set; }
public string postal_code { get; set; }
public string country { get; set; }
public string phone { get; set; }
public string fax { get; set; }
public string email { get; set; }
}
public class ShippingAddress
{
public string first_name { get; set; }
public string last_name { get; set; }
public string company { get; set; }
public string address_line_1 { get; set; }
public string address_line_2 { get; set; }
public string city { get; set; }
public string state { get; set; }
public string postal_code { get; set; }
public string country { get; set; }
public string phone { get; set; }
public string fax { get; set; }
public string email { get; set; }
}
public class Data
{
public string id { get; set; }
public string user_id { get; set; }
public string user_name { get; set; }
public string merchant_id { get; set; }
public string idempotency_key { get; set; }
public int idempotency_time { get; set; }
public string type { get; set; }
public int amount { get; set; }
public int base_amount { get; set; }
public int amount_authorized { get; set; }
public int amount_captured { get; set; }
public int amount_settled { get; set; }
public int amount_refunded { get; set; }
public int payment_adjustment { get; set; }
public int tip_amount { get; set; }
public string settlement_batch_id { get; set; }
public string processor_id { get; set; }
public string processor_type { get; set; }
public string processor_name { get; set; }
public string payment_method { get; set; }
public string payment_type { get; set; }
public List<string> features { get; set; }
public int national_tax_amount { get; set; }
public int duty_amount { get; set; }
public string ship_from_postal_code { get; set; }
public string summary_commodity_code { get; set; }
public string merchant_vat_registration_number { get; set; }
public string customer_vat_registration_number { get; set; }
public int tax_amount { get; set; }
public bool tax_exempt { get; set; }
public int shipping_amount { get; set; }
public int surcharge { get; set; }
public int discount_amount { get; set; }
public string currency { get; set; }
public string description { get; set; }
public string order_id { get; set; }
public string po_number { get; set; }
public string ip_address { get; set; }
public string transaction_source { get; set; }
public bool email_receipt { get; set; }
public string email_address { get; set; }
public string customer_id { get; set; }
public string customer_payment_type { get; set; }
public string customer_payment_ID { get; set; }
public string subscription_id { get; set; }
public string referenced_transaction_id { get; set; }
public ResponseBody response_body { get; set; }
public CustomFields custom_fields { get; set; }
public object line_items { get; set; }
public string status { get; set; }
public string response { get; set; }
public int response_code { get; set; }
public BillingAddress billing_address { get; set; }
public ShippingAddress shipping_address { get; set; }
public string created_at { get; set; }
public string updated_at { get; set; }
public string captured_at { get; set; }
public object settled_at { get; set; }
}
public class RootObject
{
public string status { get; set; }
public string msg { get; set; }
public Data data { get; set; }
}
}
It seems to work though. I did a quick compare and there are quite a few differences. Might be worth checking out.
use jsoup it is a free framework it parse the document into json format easily
`list<Element> news;
Document doc = Jsoup.connect("https://en.wikipedia.org/").get();
log(doc.title());
Elements newsHeadlines = doc.select("#mp-itn b a");
for (Element headline : news) {
log("%s\n\t%s",
headline.attr("title"), headline.absUrl("href"));
}`

C# Get Json Response into an Array

Through webrequest I am getting response text which is in Json I use Newtonsoft.Json to parse. I created classes with the help of examples from stackoverflow website but couldn't figure out how to loop whole response into an array or datatable/dataview.
JsonSerializer serializer = new JsonSerializer();
public class Link
{
public string rel { get; set; }
public string href { get; set; }
}
public class Naeringskode1
{
public string kode { get; set; }
public string beskrivelse { get; set; }
}
public class Postadresse
{
public string adresse { get; set; }
public string postnummer { get; set; }
public string poststed { get; set; }
public string kommunenummer { get; set; }
public string kommune { get; set; }
public string landkode { get; set; }
public string land { get; set; }
}
public class Beliggenhetsadresse
{
public string adresse { get; set; }
public string postnummer { get; set; }
public string poststed { get; set; }
public string kommunenummer { get; set; }
public string kommune { get; set; }
public string landkode { get; set; }
public string land { get; set; }
}
public class Link2
{
public string rel { get; set; }
public string href { get; set; }
}
public class Naeringskode2
{
public string kode { get; set; }
public string beskrivelse { get; set; }
}
public class Datum
{
public int organisasjonsnummer { get; set; }
public string navn { get; set; }
public string organisasjonsform { get; set; }
public string registreringsdatoEnhetsregisteret { get; set; }
public string registrertIMvaregisteret { get; set; }
public int antallAnsatte { get; set; }
public Naeringskode1 naeringskode1 { get; set; }
public Postadresse postadresse { get; set; }
public Beliggenhetsadresse beliggenhetsadresse { get; set; }
public int overordnetEnhet { get; set; }
public List<Link2> links { get; set; }
public string hjemmeside { get; set; }
public Naeringskode2 naeringskode2 { get; set; }
}
public class Page
{
public int size { get; set; }
public int page { get; set; }
}
public class RootObject
{
public List<Link> links { get; set; }
public List<Datum> data { get; set; }
public Page page { get; set; }
}

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