It's about the eBay API "GetOrders".
If I have more than one order in the given period of time my following code works. But if only one order is read then the "OrderArray.Order" is not an array and this gives the following exception.
Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'Order[]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Path 'GetOrdersResponse.OrderArray.Order.OrderID', line 1, position 352.'
Here my Code:
GetOrdersResponseJSON orderResp = JsonConvert.DeserializeObject<GetOrdersResponseJSON>(json);
foreach (var item in orderResp.GetOrdersResponse.OrderArray.Order)
{
Console.WriteLine(item.TransactionArray.Transaction.Buyer.Email);
}
GetOrdersResponseJSON:
using E_BAY_order_importer;
using Newtonsoft.Json;
using System;
public class GetOrdersResponseJSON
{
public Xml xml { get; set; }
public Getordersresponse GetOrdersResponse { get; set; }
}
public class Xml
{
public string version { get; set; }
public string encoding { get; set; }
}
public class Getordersresponse
{
public string xmlns { get; set; }
public DateTime Timestamp { get; set; }
public string Ack { get; set; }
public string Version { get; set; }
public string Build { get; set; }
public Paginationresult PaginationResult { get; set; }
public bool HasMoreOrders { get; set; }
public Orderarray OrderArray { get; set; }
public string OrdersPerPage { get; set; }
public string PageNumber { get; set; }
public string ReturnedOrderCountActual { get; set; }
}
public class Paginationresult
{
public string TotalNumberOfPages { get; set; }
public string TotalNumberOfEntries { get; set; }
}
public class Orderarray
{
public Order[] Order { get; set; }
}
public class Order
{
public string OrderID { get; set; }
public string OrderStatus { get; set; }
public Adjustmentamount AdjustmentAmount { get; set; }
public Amountpaid AmountPaid { get; set; }
public Amountsaved AmountSaved { get; set; }
public Checkoutstatus CheckoutStatus { get; set; }
public Shippingdetails ShippingDetails { get; set; }
public DateTime CreatedTime { get; set; }
public string SellerEmail { get; set; }
public Shippingaddress ShippingAddress { get; set; }
public Shippingserviceselected ShippingServiceSelected { get; set; }
public Subtotal Subtotal { get; set; }
public Total Total { get; set; }
public string eBayCollectAndRemitTax { get; set; }
public Transactionarray TransactionArray { get; set; }
public string BuyerUserID { get; set; }
public DateTime PaidTime { get; set; }
public DateTime ShippedTime { get; set; }
public string IntegratedMerchantCreditCardEnabled { get; set; }
public string EIASToken { get; set; }
public string PaymentHoldStatus { get; set; }
public string IsMultiLegShipping { get; set; }
public string SellerUserID { get; set; }
public string SellerEIASToken { get; set; }
public string CancelStatus { get; set; }
public string ExtendedOrderID { get; set; }
public string ContainseBayPlusTransaction { get; set; }
}
public class Adjustmentamount
{
public string currencyID { get; set; }
public string text { get; set; }
}
public class Amountpaid
{
public string currencyID { get; set; }
public string text { get; set; }
}
public class Amountsaved
{
public string currencyID { get; set; }
public string text { get; set; }
}
public class Checkoutstatus
{
public string eBayPaymentStatus { get; set; }
public DateTime LastModifiedTime { get; set; }
public string PaymentMethod { get; set; }
public string Status { get; set; }
public string IntegratedMerchantCreditCardEnabled { get; set; }
public string PaymentInstrument { get; set; }
}
public class Shippingdetails
{
public Salestax SalesTax { get; set; }
public Shippingserviceoptions ShippingServiceOptions { get; set; }
public Internationalshippingserviceoption InternationalShippingServiceOption { get; set; }
public string SellingManagerSalesRecordNumber { get; set; }
public string GetItFast { get; set; }
}
public class Salestax
{
public string SalesTaxPercent { get; set; }
public string SalesTaxState { get; set; }
public string ShippingIncludedInTax { get; set; }
public Salestaxamount SalesTaxAmount { get; set; }
}
public class Salestaxamount
{
public string currencyID { get; set; }
public string text { get; set; }
}
public class Shippingserviceoptions
{
public string ShippingService { get; set; }
public Shippingservicecost ShippingServiceCost { get; set; }
public string ShippingServicePriority { get; set; }
public string ExpeditedService { get; set; }
public string ShippingTimeMin { get; set; }
public string ShippingTimeMax { get; set; }
}
public class Shippingservicecost
{
public string currencyID { get; set; }
public string text { get; set; }
}
public class Internationalshippingserviceoption
{
public string ShippingService { get; set; }
public Shippingservicecost1 ShippingServiceCost { get; set; }
public string ShippingServicePriority { get; set; }
public string[] ShipToLocation { get; set; }
}
public class Shippingservicecost1
{
public string currencyID { get; set; }
public string text { get; set; }
}
public class Shippingaddress
{
public string Name { get; set; }
public string Street1 { get; set; }
public string Street2 { get; set; }
public string CityName { get; set; }
public string StateOrProvince { get; set; }
public string Country { get; set; }
public string CountryName { get; set; }
public string Phone { get; set; }
public string PostalCode { get; set; }
public string AddressID { get; set; }
public string AddressOwner { get; set; }
public string ExternalAddressID { get; set; }
}
public class Shippingserviceselected
{
public string ShippingService { get; set; }
public Shippingservicecost2 ShippingServiceCost { get; set; }
}
public class Shippingservicecost2
{
public string currencyID { get; set; }
public string text { get; set; }
}
public class Subtotal
{
public string currencyID { get; set; }
public string text { get; set; }
}
public class Total
{
public string currencyID { get; set; }
public string text { get; set; }
}
public class Transactionarray
{
public Transaction Transaction { get; set; }
}
public class Transaction
{
public Buyer Buyer { get; set; }
public Shippingdetails1 ShippingDetails { get; set; }
public DateTime CreatedDate { get; set; }
public Item Item { get; set; }
public string QuantityPurchased { get; set; }
public Status Status { get; set; }
public string TransactionID { get; set; }
public Transactionprice TransactionPrice { get; set; }
public string eBayCollectAndRemitTax { get; set; }
public Shippingserviceselected1 ShippingServiceSelected { get; set; }
public DateTime ShippedTime { get; set; }
public string TransactionSiteID { get; set; }
public string Platform { get; set; }
public Variation Variation { get; set; }
public Taxes Taxes { get; set; }
public string OrderLineItemID { get; set; }
public string ExtendedOrderID { get; set; }
public string eBayPlusTransaction { get; set; }
public string GuaranteedShipping { get; set; }
public string GuaranteedDelivery { get; set; }
}
public class Buyer
{
public string Email { get; set; }
public string VATStatus { get; set; }
public string UserFirstName { get; set; }
public string UserLastName { get; set; }
}
public class Shippingdetails1
{
public string SellingManagerSalesRecordNumber { get; set; }
}
public class Item
{
public string ItemID { get; set; }
public string Site { get; set; }
public string Title { get; set; }
public string ConditionID { get; set; }
public string ConditionDisplayName { get; set; }
}
public class Status
{
public string PaymentHoldStatus { get; set; }
public string InquiryStatus { get; set; }
public string ReturnStatus { get; set; }
}
public class Transactionprice
{
public string currencyID { get; set; }
public string text { get; set; }
}
public class Shippingserviceselected1
{
public Shippingpackageinfo ShippingPackageInfo { get; set; }
}
public class Shippingpackageinfo
{
public DateTime EstimatedDeliveryTimeMin { get; set; }
public DateTime EstimatedDeliveryTimeMax { get; set; }
public DateTime HandleByTime { get; set; }
public DateTime MinNativeEstimatedDeliveryTime { get; set; }
public DateTime MaxNativeEstimatedDeliveryTime { get; set; }
}
public class Variation
{
public string SKU { get; set; }
public Variationspecifics VariationSpecifics { get; set; }
public string VariationTitle { get; set; }
public string VariationViewItemURL { get; set; }
}
public class Variationspecifics
{
public Namevaluelist[] NameValueList { get; set; }
}
public class Namevaluelist
{
public string Name { get; set; }
public string Value { get; set; }
}
public class Taxes
{
public Totaltaxamount TotalTaxAmount { get; set; }
public Taxdetails TaxDetails { get; set; }
}
public class Totaltaxamount
{
public string currencyID { get; set; }
public string text { get; set; }
}
public class Taxdetails
{
public string Imposition { get; set; }
public string TaxDescription { get; set; }
public Taxamount TaxAmount { get; set; }
public Taxonsubtotalamount TaxOnSubtotalAmount { get; set; }
public Taxonshippingamount TaxOnShippingAmount { get; set; }
public Taxonhandlingamount TaxOnHandlingAmount { get; set; }
}
public class Taxamount
{
public string currencyID { get; set; }
public string text { get; set; }
}
public class Taxonsubtotalamount
{
public string currencyID { get; set; }
public string text { get; set; }
}
public class Taxonshippingamount
{
public string currencyID { get; set; }
public string text { get; set; }
}
public class Taxonhandlingamount
{
public string currencyID { get; set; }
public string text { get; set; }
}
What can I do to make it work with only one order (without array) and with multiple orders (with array)? Since I would like to continue using newtonsoft json it would be nice if I get a solution with newtonsoft json!
Here is an example of the json that I get:
// One Order I get as JSON:
[...]
"OrderArray": {
"Order": {
[...]
// Multiple Orders I get as JSON:
[...]
"OrderArray": {
"Order": [
[...]
So definitely once an array and once an object!
We can use custom JSONConverter
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace RabbitMQPoc
{
public class Program
{
public static void Main(string[] args)
{
//Multiple object test
string jsonForMultipleOrder = "{\"xml\":null,\"GetOrdersResponse\":{\"xmlns\":null,\"Timestamp\":\"0001-01-01T00:00:00\",\"Ack\":null,\"Version\":null,\"Build\":null,\"PaginationResult\":null,\"HasMoreOrders\":false,\"OrderArray\":{\"Order\":[{\"OrderID\":null,\"OrderStatus\":null,\"AdjustmentAmount\":null,\"AmountPaid\":null,\"AmountSaved\":null,\"CheckoutStatus\":null,\"ShippingDetails\":null,\"CreatedTime\":\"0001-01-01T00:00:00\",\"SellerEmail\":null,\"ShippingAddress\":null,\"ShippingServiceSelected\":null,\"Subtotal\":null,\"Total\":null,\"eBayCollectAndRemitTax\":null,\"TransactionArray\":{\"Transaction\":{\"Buyer\":{\"Email\":\"sm-a\",\"VATStatus\":null,\"UserFirstName\":null,\"UserLastName\":null},\"ShippingDetails\":null,\"CreatedDate\":\"0001-01-01T00:00:00\",\"Item\":null,\"QuantityPurchased\":null,\"Status\":null,\"TransactionID\":null,\"TransactionPrice\":null,\"eBayCollectAndRemitTax\":null,\"ShippingServiceSelected\":null,\"ShippedTime\":\"0001-01-01T00:00:00\",\"TransactionSiteID\":null,\"Platform\":null,\"Variation\":null,\"Taxes\":null,\"OrderLineItemID\":null,\"ExtendedOrderID\":null,\"eBayPlusTransaction\":null,\"GuaranteedShipping\":null,\"GuaranteedDelivery\":null}},\"BuyerUserID\":null,\"PaidTime\":\"0001-01-01T00:00:00\",\"ShippedTime\":\"0001-01-01T00:00:00\",\"IntegratedMerchantCreditCardEnabled\":null,\"EIASToken\":null,\"PaymentHoldStatus\":null,\"IsMultiLegShipping\":null,\"SellerUserID\":null,\"SellerEIASToken\":null,\"CancelStatus\":null,\"ExtendedOrderID\":null,\"ContainseBayPlusTransaction\":null},{\"OrderID\":null,\"OrderStatus\":null,\"AdjustmentAmount\":null,\"AmountPaid\":null,\"AmountSaved\":null,\"CheckoutStatus\":null,\"ShippingDetails\":null,\"CreatedTime\":\"0001-01-01T00:00:00\",\"SellerEmail\":null,\"ShippingAddress\":null,\"ShippingServiceSelected\":null,\"Subtotal\":null,\"Total\":null,\"eBayCollectAndRemitTax\":null,\"TransactionArray\":{\"Transaction\":{\"Buyer\":{\"Email\":\"darshana\",\"VATStatus\":null,\"UserFirstName\":null,\"UserLastName\":null},\"ShippingDetails\":null,\"CreatedDate\":\"0001-01-01T00:00:00\",\"Item\":null,\"QuantityPurchased\":null,\"Status\":null,\"TransactionID\":null,\"TransactionPrice\":null,\"eBayCollectAndRemitTax\":null,\"ShippingServiceSelected\":null,\"ShippedTime\":\"0001-01-01T00:00:00\",\"TransactionSiteID\":null,\"Platform\":null,\"Variation\":null,\"Taxes\":null,\"OrderLineItemID\":null,\"ExtendedOrderID\":null,\"eBayPlusTransaction\":null,\"GuaranteedShipping\":null,\"GuaranteedDelivery\":null}},\"BuyerUserID\":null,\"PaidTime\":\"0001-01-01T00:00:00\",\"ShippedTime\":\"0001-01-01T00:00:00\",\"IntegratedMerchantCreditCardEnabled\":null,\"EIASToken\":null,\"PaymentHoldStatus\":null,\"IsMultiLegShipping\":null,\"SellerUserID\":null,\"SellerEIASToken\":null,\"CancelStatus\":null,\"ExtendedOrderID\":null,\"ContainseBayPlusTransaction\":null}]},\"OrdersPerPage\":null,\"PageNumber\":null,\"ReturnedOrderCountActual\":null}}";
GetOrdersResponseJSON orderResp = JsonConvert.DeserializeObject<GetOrdersResponseJSON>(jsonForMultipleOrder);
foreach (var item in orderResp.GetOrdersResponse.OrderArray.Order)
{
Console.WriteLine("From Mutiple order-> Email:" + item.TransactionArray.Transaction.Buyer.Email);
}
//Single object test
string jsonForSingleOrder = "{\"xml\":null,\"GetOrdersResponse\":{\"xmlns\":null,\"Timestamp\":\"0001-01-01T00:00:00\",\"Ack\":null,\"Version\":null,\"Build\":null,\"PaginationResult\":null,\"HasMoreOrders\":false,\"OrderArray\":{\"Order\":{\"OrderID\":null,\"OrderStatus\":null,\"AdjustmentAmount\":null,\"AmountPaid\":null,\"AmountSaved\":null,\"CheckoutStatus\":null,\"ShippingDetails\":null,\"CreatedTime\":\"0001-01-01T00:00:00\",\"SellerEmail\":null,\"ShippingAddress\":null,\"ShippingServiceSelected\":null,\"Subtotal\":null,\"Total\":null,\"eBayCollectAndRemitTax\":null,\"TransactionArray\":{\"Transaction\":{\"Buyer\":{\"Email\":\"darshana\",\"VATStatus\":null,\"UserFirstName\":null,\"UserLastName\":null},\"ShippingDetails\":null,\"CreatedDate\":\"0001-01-01T00:00:00\",\"Item\":null,\"QuantityPurchased\":null,\"Status\":null,\"TransactionID\":null,\"TransactionPrice\":null,\"eBayCollectAndRemitTax\":null,\"ShippingServiceSelected\":null,\"ShippedTime\":\"0001-01-01T00:00:00\",\"TransactionSiteID\":null,\"Platform\":null,\"Variation\":null,\"Taxes\":null,\"OrderLineItemID\":null,\"ExtendedOrderID\":null,\"eBayPlusTransaction\":null,\"GuaranteedShipping\":null,\"GuaranteedDelivery\":null}},\"BuyerUserID\":null,\"PaidTime\":\"0001-01-01T00:00:00\",\"ShippedTime\":\"0001-01-01T00:00:00\",\"IntegratedMerchantCreditCardEnabled\":null,\"EIASToken\":null,\"PaymentHoldStatus\":null,\"IsMultiLegShipping\":null,\"SellerUserID\":null,\"SellerEIASToken\":null,\"CancelStatus\":null,\"ExtendedOrderID\":null,\"ContainseBayPlusTransaction\":null}},\"OrdersPerPage\":null,\"PageNumber\":null,\"ReturnedOrderCountActual\":null}}";
GetOrdersResponseJSON ordersResponseJSONForSingleOrder = JsonConvert.DeserializeObject<GetOrdersResponseJSON>(jsonForSingleOrder);
foreach (var item in ordersResponseJSONForSingleOrder.GetOrdersResponse.OrderArray.Order)
{
Console.WriteLine("From single order-> Email:"+item.TransactionArray.Transaction.Buyer.Email);
}
}
class SingleOrArrayConverter<T> : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(List<T>));
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JToken token = JToken.Load(reader);
if (token.Type == JTokenType.Array)
{
return token.ToObject<List<T>>();
}
return new List<T> { token.ToObject<T>() };
}
public override bool CanWrite
{
get { return false; }
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
public class GetOrdersResponseJSON
{
public Xml xml { get; set; }
public Getordersresponse GetOrdersResponse { get; set; }
}
public class Xml
{
public string version { get; set; }
public string encoding { get; set; }
}
public class Getordersresponse
{
public string xmlns { get; set; }
public DateTime Timestamp { get; set; }
public string Ack { get; set; }
public string Version { get; set; }
public string Build { get; set; }
public Paginationresult PaginationResult { get; set; }
public bool HasMoreOrders { get; set; }
public Orderarray OrderArray { get; set; }
public string OrdersPerPage { get; set; }
public string PageNumber { get; set; }
public string ReturnedOrderCountActual { get; set; }
}
public class Paginationresult
{
public string TotalNumberOfPages { get; set; }
public string TotalNumberOfEntries { get; set; }
}
public class Orderarray
{
[JsonConverter(typeof(SingleOrArrayConverter<Order>))]
public List<Order> Order { get; set; }
}
public class Order
{
public string OrderID { get; set; }
public string OrderStatus { get; set; }
public Adjustmentamount AdjustmentAmount { get; set; }
public Amountpaid AmountPaid { get; set; }
public Amountsaved AmountSaved { get; set; }
public Checkoutstatus CheckoutStatus { get; set; }
public Shippingdetails ShippingDetails { get; set; }
public DateTime CreatedTime { get; set; }
public string SellerEmail { get; set; }
public Shippingaddress ShippingAddress { get; set; }
public Shippingserviceselected ShippingServiceSelected { get; set; }
public Subtotal Subtotal { get; set; }
public Total Total { get; set; }
public string eBayCollectAndRemitTax { get; set; }
public Transactionarray TransactionArray { get; set; }
public string BuyerUserID { get; set; }
public DateTime PaidTime { get; set; }
public DateTime ShippedTime { get; set; }
public string IntegratedMerchantCreditCardEnabled { get; set; }
public string EIASToken { get; set; }
public string PaymentHoldStatus { get; set; }
public string IsMultiLegShipping { get; set; }
public string SellerUserID { get; set; }
public string SellerEIASToken { get; set; }
public string CancelStatus { get; set; }
public string ExtendedOrderID { get; set; }
public string ContainseBayPlusTransaction { get; set; }
}
public class Adjustmentamount
{
public string currencyID { get; set; }
public string text { get; set; }
}
public class Amountpaid
{
public string currencyID { get; set; }
public string text { get; set; }
}
public class Amountsaved
{
public string currencyID { get; set; }
public string text { get; set; }
}
public class Checkoutstatus
{
public string eBayPaymentStatus { get; set; }
public DateTime LastModifiedTime { get; set; }
public string PaymentMethod { get; set; }
public string Status { get; set; }
public string IntegratedMerchantCreditCardEnabled { get; set; }
public string PaymentInstrument { get; set; }
}
public class Shippingdetails
{
public Salestax SalesTax { get; set; }
public Shippingserviceoptions ShippingServiceOptions { get; set; }
public Internationalshippingserviceoption InternationalShippingServiceOption { get; set; }
public string SellingManagerSalesRecordNumber { get; set; }
public string GetItFast { get; set; }
}
public class Salestax
{
public string SalesTaxPercent { get; set; }
public string SalesTaxState { get; set; }
public string ShippingIncludedInTax { get; set; }
public Salestaxamount SalesTaxAmount { get; set; }
}
public class Salestaxamount
{
public string currencyID { get; set; }
public string text { get; set; }
}
public class Shippingserviceoptions
{
public string ShippingService { get; set; }
public Shippingservicecost ShippingServiceCost { get; set; }
public string ShippingServicePriority { get; set; }
public string ExpeditedService { get; set; }
public string ShippingTimeMin { get; set; }
public string ShippingTimeMax { get; set; }
}
public class Shippingservicecost
{
public string currencyID { get; set; }
public string text { get; set; }
}
public class Internationalshippingserviceoption
{
public string ShippingService { get; set; }
public Shippingservicecost1 ShippingServiceCost { get; set; }
public string ShippingServicePriority { get; set; }
public string[] ShipToLocation { get; set; }
}
public class Shippingservicecost1
{
public string currencyID { get; set; }
public string text { get; set; }
}
public class Shippingaddress
{
public string Name { get; set; }
public string Street1 { get; set; }
public string Street2 { get; set; }
public string CityName { get; set; }
public string StateOrProvince { get; set; }
public string Country { get; set; }
public string CountryName { get; set; }
public string Phone { get; set; }
public string PostalCode { get; set; }
public string AddressID { get; set; }
public string AddressOwner { get; set; }
public string ExternalAddressID { get; set; }
}
public class Shippingserviceselected
{
public string ShippingService { get; set; }
public Shippingservicecost2 ShippingServiceCost { get; set; }
}
public class Shippingservicecost2
{
public string currencyID { get; set; }
public string text { get; set; }
}
public class Subtotal
{
public string currencyID { get; set; }
public string text { get; set; }
}
public class Total
{
public string currencyID { get; set; }
public string text { get; set; }
}
public class Transactionarray
{
public Transaction Transaction { get; set; }
}
public class Transaction
{
public Buyer Buyer { get; set; }
public Shippingdetails1 ShippingDetails { get; set; }
public DateTime CreatedDate { get; set; }
public Item Item { get; set; }
public string QuantityPurchased { get; set; }
public Status Status { get; set; }
public string TransactionID { get; set; }
public Transactionprice TransactionPrice { get; set; }
public string eBayCollectAndRemitTax { get; set; }
public Shippingserviceselected1 ShippingServiceSelected { get; set; }
public DateTime ShippedTime { get; set; }
public string TransactionSiteID { get; set; }
public string Platform { get; set; }
public Variation Variation { get; set; }
public Taxes Taxes { get; set; }
public string OrderLineItemID { get; set; }
public string ExtendedOrderID { get; set; }
public string eBayPlusTransaction { get; set; }
public string GuaranteedShipping { get; set; }
public string GuaranteedDelivery { get; set; }
}
public class Buyer
{
public string Email { get; set; }
public string VATStatus { get; set; }
public string UserFirstName { get; set; }
public string UserLastName { get; set; }
}
public class Shippingdetails1
{
public string SellingManagerSalesRecordNumber { get; set; }
}
public class Item
{
public string ItemID { get; set; }
public string Site { get; set; }
public string Title { get; set; }
public string ConditionID { get; set; }
public string ConditionDisplayName { get; set; }
}
public class Status
{
public string PaymentHoldStatus { get; set; }
public string InquiryStatus { get; set; }
public string ReturnStatus { get; set; }
}
public class Transactionprice
{
public string currencyID { get; set; }
public string text { get; set; }
}
public class Shippingserviceselected1
{
public Shippingpackageinfo ShippingPackageInfo { get; set; }
}
public class Shippingpackageinfo
{
public DateTime EstimatedDeliveryTimeMin { get; set; }
public DateTime EstimatedDeliveryTimeMax { get; set; }
public DateTime HandleByTime { get; set; }
public DateTime MinNativeEstimatedDeliveryTime { get; set; }
public DateTime MaxNativeEstimatedDeliveryTime { get; set; }
}
public class Variation
{
public string SKU { get; set; }
public Variationspecifics VariationSpecifics { get; set; }
public string VariationTitle { get; set; }
public string VariationViewItemURL { get; set; }
}
public class Variationspecifics
{
public Namevaluelist[] NameValueList { get; set; }
}
public class Namevaluelist
{
public string Name { get; set; }
public string Value { get; set; }
}
public class Taxes
{
public Totaltaxamount TotalTaxAmount { get; set; }
public Taxdetails TaxDetails { get; set; }
}
public class Totaltaxamount
{
public string currencyID { get; set; }
public string text { get; set; }
}
public class Taxdetails
{
public string Imposition { get; set; }
public string TaxDescription { get; set; }
public Taxamount TaxAmount { get; set; }
public Taxonsubtotalamount TaxOnSubtotalAmount { get; set; }
public Taxonshippingamount TaxOnShippingAmount { get; set; }
public Taxonhandlingamount TaxOnHandlingAmount { get; set; }
}
public class Taxamount
{
public string currencyID { get; set; }
public string text { get; set; }
}
public class Taxonsubtotalamount
{
public string currencyID { get; set; }
public string text { get; set; }
}
public class Taxonshippingamount
{
public string currencyID { get; set; }
public string text { get; set; }
}
public class Taxonhandlingamount
{
public string currencyID { get; set; }
public string text { get; set; }
}
}
}
As answered here How to handle both a single item and an array for the same property using JSON.net
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"));
}`
I have created classes needed by help of a website, but can't deserialize.
public class Brand
{
public string name { get; set; }
}
public class Link
{
public string href { get; set; }
}
public class Price
{
public double current { get; set; }
}
public class RootObject
{
public Brand brand { get; set; }
public string href { get; set; }
public List<Link> links { get; set; }
public List<string> mpns { get; set; }
public string name { get; set; }
public Price price { get; set; }
public string productId { get; set; }
}
How I am trying in C#
string API = "https://www.verkkokauppa.com/resp-api/product?pids=552952"
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(API);
request.Method = "GET";
string result = "";
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
result = reader.ReadToEnd();
reader.Close();
dataStream.Close();
}
var jsonresult = JsonConvert.DeserializeObject<RootObject>(result);
foreach (Brand p in jsonresult)
{
Debug.WriteLine(p);
}
I know I'm doing something wrong, but can anyone help me to correctly get the elements from the classes above only?
There are few mistakes in the code you've provided:
The json which is received from endpoint, is a json array.
So, instead of deserialzing as RootObject you should deserialize as List<RootObject>.
While iterating through jsonresult you should use RootObject instead of Brand
So here is the complete solution:
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.Net;
using System.IO;
using System.Diagnostics;
public class Brand
{
public string name { get; set; }
}
public class Link
{
public string href { get; set; }
}
public class Price
{
public double current { get; set; }
}
public class RootObject
{
public Brand brand { get; set; }
public string href { get; set; }
public List<Link> links { get; set; }
public List<string> mpns { get; set; }
public string name { get; set; }
public Price price { get; set; }
public string productId { get; set; }
}
public class Program
{
public static void Main()
{
string API = "https://www.verkkokauppa.com/resp-api/product?pids=552952";
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(API);
request.Method = "GET";
string result = "";
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
result = reader.ReadToEnd();
reader.Close();
dataStream.Close();
}
var jsonresult = JsonConvert.DeserializeObject<List<RootObject>>(result);
foreach (RootObject p in jsonresult)
{
Debug.WriteLine(p.brand.name);
foreach (Link link in p.links){
Debug.WriteLine(link.href);
}
foreach (string mpn in p.mpns){
Debug.WriteLine(mpn);
}
}
}
}
And here is the online version just in case it's needed.
Finally, I did it.kindly change your Model. The model should match your JSON data. You can check the complete solution
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
namespace Jsondemo
{
public class Brand
{
public int id { get; set; }
public string name { get; set; }
public string slug { get; set; }
public string support { get; set; }
public string url { get; set; }
}
public class Path
{
public string id { get; set; }
public string name { get; set; }
}
public class Category
{
public string id { get; set; }
public string name { get; set; }
public string slug { get; set; }
public List<Path> path { get; set; }
}
public class Installment
{
public int months { get; set; }
public int monthlySum { get; set; }
public double totalAmount { get; set; }
public double annualInterestRate { get; set; }
public double interest { get; set; }
public double fee { get; set; }
}
public class UiLabels
{
public string text { get; set; }
public string price { get; set; }
public string time { get; set; }
public List<string> tooltip { get; set; }
}
public class Installment2
{
public int months { get; set; }
public string monthlySum { get; set; }
public double totalAmount { get; set; }
public double annualInterestRate { get; set; }
public double interest { get; set; }
public double fee { get; set; }
}
public class UiLabels2
{
public string text { get; set; }
public string price { get; set; }
public string time { get; set; }
public List<string> tooltip { get; set; }
}
public class CompanyFinancing
{
public List<Installment2> installments { get; set; }
public UiLabels2 uiLabels { get; set; }
}
public class Financing
{
public List<Installment> installments { get; set; }
public string type { get; set; }
public double price { get; set; }
public UiLabels uiLabels { get; set; }
public CompanyFinancing companyFinancing { get; set; }
}
public class Image
{
public string __invalid_name__45 { get; set; }
public string __invalid_name__90 { get; set; }
public string __invalid_name__300 { get; set; }
public string __invalid_name__500 { get; set; }
public string __invalid_name__960 { get; set; }
public string orig { get; set; }
}
public class Link
{
public string name { get; set; }
public string type { get; set; }
public string href { get; set; }
}
public class Package
{
public int width { get; set; }
public int height { get; set; }
public int depth { get; set; }
public int volume { get; set; }
public int weight { get; set; }
}
public class Price
{
public double current { get; set; }
public double currentTaxless { get; set; }
public string currentFormatted { get; set; }
public double original { get; set; }
public double originalTaxless { get; set; }
public string originalFormatted { get; set; }
public object discountAmount { get; set; }
public object discountPercentage { get; set; }
public int taxRate { get; set; }
public object discount { get; set; }
public object deposit { get; set; }
public object unit { get; set; }
}
public class Rating
{
public int reviewCount { get; set; }
public int averageOverallRating { get; set; }
public int recommendedCount { get; set; }
}
public class Relations
{
public List<object> recommended { get; set; }
public List<object> newer { get; set; }
public List<object> older { get; set; }
public List<object> bundles { get; set; }
}
public class Restrictions
{
public bool isRestricted { get; set; }
public List<object> pickupAllowed { get; set; }
public List<object> postalCodeAllowed { get; set; }
public string description { get; set; }
public string descriptionShort { get; set; }
}
public class ShipmentPrice
{
public int id { get; set; }
public string name { get; set; }
public double price { get; set; }
public bool pickup { get; set; }
}
public class Js
{
public int stock { get; set; }
public string stockStatus { get; set; }
}
public class Pak
{
public int stock { get; set; }
public string stockStatus { get; set; }
}
public class Vendor
{
public int stock { get; set; }
public string stockStatus { get; set; }
}
public class Warehouses
{
public Js js { get; set; }
public Pak pak { get; set; }
public Vendor vendor { get; set; }
}
public class Web
{
public bool isAvailable { get; set; }
public bool isPurchasable { get; set; }
public int stock { get; set; }
public string stockStatus { get; set; }
public int minDays { get; set; }
public int maxDays { get; set; }
public Warehouses warehouses { get; set; }
public string ranking { get; set; }
}
public class Js2
{
public bool isAvailable { get; set; }
public bool isPurchasable { get; set; }
public int stock { get; set; }
public string stockStatus { get; set; }
public int minDays { get; set; }
public int maxDays { get; set; }
}
public class JsKioski
{
public bool isAvailable { get; set; }
public bool isPurchasable { get; set; }
public int stock { get; set; }
public string stockStatus { get; set; }
public int minDays { get; set; }
public int maxDays { get; set; }
}
public class Oul
{
public bool isAvailable { get; set; }
public bool isPurchasable { get; set; }
public int stock { get; set; }
public string stockStatus { get; set; }
public int minDays { get; set; }
public int maxDays { get; set; }
}
public class Pir
{
public bool isAvailable { get; set; }
public bool isPurchasable { get; set; }
public int stock { get; set; }
public string stockStatus { get; set; }
public int minDays { get; set; }
public int maxDays { get; set; }
}
public class Rai
{
public bool isAvailable { get; set; }
public bool isPurchasable { get; set; }
public int stock { get; set; }
public string stockStatus { get; set; }
public int minDays { get; set; }
public int maxDays { get; set; }
}
public class Pu1
{
public bool isAvailable { get; set; }
public bool isPurchasable { get; set; }
public int stock { get; set; }
public string stockStatus { get; set; }
public int minDays { get; set; }
public int maxDays { get; set; }
}
public class Pu2
{
public bool isAvailable { get; set; }
public bool isPurchasable { get; set; }
public int stock { get; set; }
public string stockStatus { get; set; }
public int minDays { get; set; }
public int maxDays { get; set; }
}
public class Pu3
{
public bool isAvailable { get; set; }
public bool isPurchasable { get; set; }
public int stock { get; set; }
public string stockStatus { get; set; }
public int minDays { get; set; }
public int maxDays { get; set; }
}
public class Pu4
{
public bool isAvailable { get; set; }
public bool isPurchasable { get; set; }
public int stock { get; set; }
public string stockStatus { get; set; }
public int minDays { get; set; }
public int maxDays { get; set; }
}
public class Stores
{
public Js2 js { get; set; }
public JsKioski js_kioski { get; set; }
public Oul oul { get; set; }
public Pir pir { get; set; }
public Rai rai { get; set; }
public Pu1 pu1 { get; set; }
public Pu2 pu2 { get; set; }
public Pu3 pu3 { get; set; }
public Pu4 pu4 { get; set; }
}
public class Stocks
{
public Web web { get; set; }
public Stores stores { get; set; }
}
public class Availability
{
public string _id { get; set; }
public int pid { get; set; }
public object overrideText { get; set; }
public bool isElectronic { get; set; }
public bool isVirtual { get; set; }
public bool isInStoresOnly { get; set; }
public bool isReleased { get; set; }
public bool isShippingAllowed { get; set; }
public bool isPickupAllowed { get; set; }
public bool isStockVisible { get; set; }
public bool isPurchasable { get; set; }
public bool isSoldOut { get; set; }
public bool isEOL { get; set; }
public bool isFastDeliveryAvailable { get; set; }
public bool isStoreOrderAllowed { get; set; }
public bool hasStock { get; set; }
public Stocks stocks { get; set; }
public List<object> tags { get; set; }
public DateTime updatedAt { get; set; }
public DateTime verifiedAt { get; set; }
public int updateCount { get; set; }
public DateTime updateStartTime { get; set; }
}
public class RootObject
{
public string _id { get; set; }
public bool active { get; set; }
public int ageLimit { get; set; }
public Brand brand { get; set; }
public List<string> bulletPoints { get; set; }
public List<object> bundleProducts { get; set; }
public List<object> campaigns { get; set; }
public List<string> categories { get; set; }
public Category category { get; set; }
public DateTime createdAt { get; set; }
public List<object> demoLocations { get; set; }
public string description { get; set; }
public string descriptionShort { get; set; }
public List<string> eans { get; set; }
public bool electronic { get; set; }
public Financing financing { get; set; }
public string freeShipmentFor { get; set; }
public bool hidePriceEstimate { get; set; }
public string href { get; set; }
public List<Image> images { get; set; }
public List<Link> links { get; set; }
public object maxAmountPerOrder { get; set; }
public List<string> mpns { get; set; }
public string name { get; set; }
public Package package { get; set; }
public int pid { get; set; }
public Price price { get; set; }
public string productId { get; set; }
public Rating rating { get; set; }
public Relations relations { get; set; }
public DateTime releasedAt { get; set; }
public Restrictions restrictions { get; set; }
public List<string> ribbons { get; set; }
public List<ShipmentPrice> shipmentPrices { get; set; }
public List<object> shopAreas { get; set; }
public bool vak { get; set; }
public int visible { get; set; }
public string warranty { get; set; }
public DateTime updatedAt { get; set; }
public DateTime verifiedAt { get; set; }
public int updateCount { get; set; }
public DateTime updateStartTime { get; set; }
public Availability availability { get; set; }
}
class Program
{
static void Main(string[] args)
{
string API = "https://www.verkkokauppa.com/resp-api/product?pids=552952";
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(API);
request.Method = "GET";
string result = "";
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
result = reader.ReadToEnd();
reader.Close();
dataStream.Close();
}
var jsonresult = JsonConvert.DeserializeObject<List<RootObject>>(result);
foreach (RootObject p in jsonresult)
{
foreach (var item in p.links)
{
Debug.WriteLine(item.href);
}
}
Console.WriteLine("Hello World!");
}
}
}
You can use https://quicktype.io to generate c# code with entities from JSON.
i have created the c# classes for your json request.
https://app.quicktype.io?share=KNyJfG7rGBZH96H6yNXe
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.