I faced the problem: Cannot deserialize the current JSON object.
As follows:
public List<Track> Tracks { get; set; }
public async Task<List<Track>> GetTracking()
{
using (var httpClient = new HttpClient())
{
using (var requests = new HttpRequestMessage(new HttpMethod("GET"), "urlxxxxxxxx..."))
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
requests.Headers.TryAddWithoutValidation("accept", "application/json");
var response = await httpClient.SendAsync(requests);
using (HttpContent content = response.Content)
{
var jsonStr = content.ReadAsStringAsync().GetAwaiter().GetResult();
var res = JsonConvert.DeserializeObject<List<Track>>(jsonStr); //Get Error**
Tracks = res;
}
}
}
return Tracks;
}
Model Class
public class Track
{
public List<Events> events { get; set; }
}
public class Events
{
public string eventID { get; set; }
public string eventType { get; set; }
public string eventDateTime { get; set; }
public string eventCreatedDateTime { get; set; }
public string eventClassifierCode { get; set; }
public string transportEventTypeCode { get; set; }
public string documentID { get; set; }
public string shipmentEventTypeCode { get; set; }
public List<DocumentReferences> documentReferences { get; set; }
public TransportCall transportCall { get; set; }
}
public class DocumentReferencesMearsk
{
public string documentReferenceType { get; set; }
public string documentReferenceValue { get; set; }
}
public class TransportCallMaersk
{
public string transportCallID { get; set; }
public string carrierServiceCode { get; set; }
public string exportVoyageNumber { get; set; }
public string importVoyageNumber { get; set; }
public int transportCallSequenceNumber { get; set; }
public string UNLocationCode { get; set; }
public string facilityCode { get; set; }
public string facilityCodeListProvider { get; set; }
public string facilityTypeCode { get; set; }
public string otherFacility { get; set; }
public string modeOfTransport { get; set; }
public LocationMearsk location { get; set; }
public VesselMearsk vessel { get; set; }
}
My input data:
https://drive.google.com/file/d/12g0nHkHlmbU4Af8crHlzKXD_ERIZdCyH/view?usp=sharing
As in my description. I get the error: I get the error: Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[XX. Models.Track]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
Even though I declared: public List events { get; set; }
Is the problem I have misunderstood the format of DeserializeObject. Looking forward to everyone's help. Thank
you have an object, not an array
var res = JsonConvert.DeserializeObject<Track>(jsonStr);
and fix class
public class Events
{
....
public List<DocumentReferencesMearsk> documentReferences { get; set; }
public TransportCallMaersk transportCall { get; set; }
}
Your model is incomplete and has typos. Assuming you have the correct versions of them.
You are doing:
var res = JsonConvert.DeserializeObject<List<Track>>(jsonStr);
which should be just:
var res = JsonConvert.DeserializeObject<Track>(jsonStr);
Your json doesn't have an array at the root level.
Full working sample:
void Main()
{
var res = JsonConvert.DeserializeObject<Track>(myJson);
}
public class Track
{
public List<Events> events { get; set; }
}
public class Events
{
public string eventID { get; set; }
public string eventType { get; set; }
public string eventDateTime { get; set; }
public string eventCreatedDateTime { get; set; }
public string eventClassifierCode { get; set; }
public string transportEventTypeCode { get; set; }
public string documentID { get; set; }
public string shipmentEventTypeCode { get; set; }
public List<DocumentReferencesMearsk> documentReferences { get; set; }
public TransportCallMaersk transportCall { get; set; }
}
public class DocumentReferencesMearsk
{
public string documentReferenceType { get; set; }
public string documentReferenceValue { get; set; }
}
public class TransportCallMaersk
{
public string transportCallID { get; set; }
public string carrierServiceCode { get; set; }
public string exportVoyageNumber { get; set; }
public string importVoyageNumber { get; set; }
public int transportCallSequenceNumber { get; set; }
public string UNLocationCode { get; set; }
public string facilityCode { get; set; }
public string facilityCodeListProvider { get; set; }
public string facilityTypeCode { get; set; }
public string otherFacility { get; set; }
public string modeOfTransport { get; set; }
public Location location { get; set; }
public Vessel vessel { get; set; }
}
public partial class Location
{
public string LocationName { get; set; }
public string Latitude { get; set; }
public string Longitude { get; set; }
public string UnLocationCode { get; set; }
public string FacilityCode { get; set; }
public string FacilityCodeListProvider { get; set; }
}
public partial class Vessel
{
public long VesselImoNumber { get; set; }
public string VesselName { get; set; }
public string VesselFlag { get; set; }
public string VesselCallSignNumber { get; set; }
public string VesselOperatorCarrierCode { get; set; }
public string VesselOperatorCarrierCodeListProvider { get; set; }
}
static readonly string myJson = #"{
""events"": [
{
""eventID"": ""6832920321"",
""eventType"": ""SHIPMENT"",
""eventDateTime"": ""2019-11-12T07:41:00+08:00"",
""eventCreatedDateTime"": ""2021-01-09T14:12:56Z"",
""eventClassifierCode"": ""ACT"",
""shipmentEventTypeCode"": ""DRFT"",
""documentTypeCode"": ""SHI"",
""documentID"": ""205284917""
},
{
""eventID"": ""6832920321"",
""eventType"": ""TRANSPORT"",
""eventDateTime"": ""2019-11-12T07:41:00+08:00"",
""eventCreatedDateTime"": ""2021-01-09T14:12:56Z"",
""eventClassifierCode"": ""ACT"",
""transportEventTypeCode"": ""ARRI"",
""documentReferences"": [
{
""documentReferenceType"": ""BKG"",
""documentReferenceValue"": ""ABC123123123""
},
{
""documentReferenceType"": ""TRD"",
""documentReferenceValue"": ""85943567-eedb-98d3-f4ed-aed697474ed4""
}
],
""transportCall"": {
""transportCallID"": ""123e4567-e89b-12d3-a456-426614174000"",
""carrierServiceCode"": ""FE1"",
""exportVoyageNumber"": ""2103S"",
""importVoyageNumber"": ""2103N"",
""transportCallSequenceNumber"": 2,
""UNLocationCode"": ""USNYC"",
""facilityCode"": ""ADT"",
""facilityCodeListProvider"": ""SMDG"",
""facilityTypeCode"": ""POTE"",
""otherFacility"": ""Balboa Port Terminal, Avenida Balboa Panama"",
""modeOfTransport"": ""VESSEL"",
""location"": {
""locationName"": ""Eiffel Tower"",
""latitude"": ""48.8585500"",
""longitude"": ""2.294492036"",
""UNLocationCode"": ""USNYC"",
""facilityCode"": ""ADT"",
""facilityCodeListProvider"": ""SMDG""
},
""vessel"": {
""vesselIMONumber"": 1801323,
""vesselName"": ""King of the Seas"",
""vesselFlag"": ""DE"",
""vesselCallSignNumber"": ""NCVV"",
""vesselOperatorCarrierCode"": ""MAEU"",
""vesselOperatorCarrierCodeListProvider"": ""NMFTA""
}
}
}
]
}";
EDIT: Result is something like:
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 have this json
and i want to deserialize it so I can get each object's value for example:
"icon_url": "-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgpouLWzKjhzw8zFdC5K092kl5SClMj3PLXFhGpC_Pp8j-3I4IG7i1Hn_UI-Nmj3ItDGe1BoN1mCr1G4xL_vhMS8tcmcn3JhuihwsHvbzQv3309k3tBw8A",
The problem is I can make the class(es) that I need so I can deserialize the json because the json string has nested objects.
I used json2csharp to help me generate classes. After some merging and cleaning up, this is what I got:
public class InventoryItem
{
public string id { get; set; }
public string classid { get; set; }
public string instanceid { get; set; }
public string amount { get; set; }
public int pos { get; set; }
}
public class AppData
{
public string def_index { get; set; }
public int? is_itemset_name { get; set; }
public int? limited { get; set; }
}
public class Description
{
public string type { get; set; }
public string value { get; set; }
public string color { get; set; }
public AppData app_data { get; set; }
}
public class Action
{
public string name { get; set; }
public string link { get; set; }
}
public class Tag
{
public string internal_name { get; set; }
public string name { get; set; }
public string category { get; set; }
public string category_name { get; set; }
public string color { get; set; }
}
public class RgDescription
{
public string appid { get; set; }
public string classid { get; set; }
public string instanceid { get; set; }
public string icon_url { get; set; }
public string icon_url_large { get; set; }
public string icon_drag_url { get; set; }
public string name { get; set; }
public string market_hash_name { get; set; }
public string market_name { get; set; }
public string name_color { get; set; }
public string background_color { get; set; }
public string type { get; set; }
public int tradable { get; set; }
public int marketable { get; set; }
public int commodity { get; set; }
public string market_tradable_restriction { get; set; }
public List<Description> descriptions { get; set; }
public List<Action> actions { get; set; }
public List<Action> market_actions { get; set; }
public List<Tag> tags { get; set; }
}
public class RootObject
{
public bool success { get; set; }
public IDictionary<string, InventoryItem> rgInventory { get; set; }
public List<object> rgCurrency { get; set; }
public IDictionary<string, RgDescription> rgDescriptions { get; set; }
public bool more { get; set; }
public bool more_start { get; set; }
}
These appear to work correctly, you can deserialize and serialize with code like this:
var obj = JsonConvert.DeserializeObject<RootObject>(oldString);
Console.WriteLine(obj.rgDescriptions["310776560_302028390"].icon_url); // e.g.
var newString = JsonConvert.SerializeObject(obj,
new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
// null value handling is optional, the above makes it a little more like the source string