Deserialize JSON using NewtonSoft - c#

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

Related

App is freezing when trying to deserialize Json string to object

I'm not sure what is causing this to happen. When debugging, I can step through each line, but when it hits the DeserializeObject line, the program doesn't do anything. I can no longer step over or do anything else with the program. No error messages are being thrown either.
[Command("stats")]
public async Task LookupMonsterStats(CommandContext ctx, string name)
{
string monstersUri = "https://www.dnd5eapi.co/api/monsters/";
var formatted = name.Replace(" ", "-");
string apiResponse = string.Empty;
using (var httpClient = new HttpClient())
{
using (var response = await httpClient.GetAsync(monstersUri + formatted))
{
apiResponse = await response.Content.ReadAsStringAsync();
var monster = JsonConvert.DeserializeObject<Monster>(apiResponse);
}
}
await ctx.Channel.SendMessageAsync(apiResponse).ConfigureAwait(false);
}
Edit: Here is what my Monster class looks like
public class Monster
{
[JsonProperty("index")]
public string Index { get; set; }
[JsonProperty("name")]
public string Name{ get; set; }
[JsonProperty("size")]
public string Size { get; set; }
[JsonProperty("type")]
public string Type { get; set; }
[JsonProperty("subtype")]
public string Subtype { get; set; }
[JsonProperty("alignment")]
public string Alignment { get; set; }
[JsonProperty("armor_class")]
public int? ArmorClass { get; set; }
[JsonProperty("hit_points")]
public int? HitPoints { get; set; }
[JsonProperty("forms")]
public List<string> Forms { get; set; }
[JsonProperty("speed")]
public Object Speed { get; set; }
[JsonProperty("strength")]
public int? Strength { get; set; }
[JsonProperty("dexterity")]
public int? Dexterity { get; set; }
[JsonProperty("constitution")]
public int? Constitution { get; set; }
[JsonProperty("intelligence")]
public int? Intelligence { get; set; }
[JsonProperty("wisdom")]
public int? Wisdom { get; set; }
[JsonProperty("charisma")]
public int? Charisma { get; set; }
[JsonProperty("proficiencies")]
public List<string> Proficiencies { get; set; }
[JsonProperty("damage_vulnerabilities")]
public List<string> DamageVulnerabilities { get; set; }
[JsonProperty("damage_resistances")]
public List<string> DamageResistances { get; set; }
[JsonProperty("damage_immunities")]
public List<string> DamageImmunities { get; set; }
[JsonProperty("condition_immunities")]
public List<string> ConditionImmunities { get; set; }
[JsonProperty("senses")]
public Object Senses { get; set; }
[JsonProperty("languages")]
public string Languages { get; set; }
[JsonProperty("challenge_rating")]
public decimal? ChallengeRating { get; set; }
[JsonProperty("special_abilities")]
public List<string> SpecialAbilities { get; set; }
[JsonProperty("actions")]
public List<string> Actions { get; set; }
[JsonProperty("legendary_actions")]
public List<string> LegendaryActions { get; set; }
[JsonProperty("url")]
public string Url { get; set; }
}
As mentioned in a comment your class definition doesn't seem to match the JSON response, assuming you're using Visual Studio it's probably worth opening Debug / Windows / Exception Settings and make sure "Common Language Runtime Exceptions" is checked. Sometimes I've found stepping over in multi-threaded apps can produce unusual results after an exception.
When I pasted your code into LINQPad I got errors on several members you've defined as List<string> when the underlying type is more complex. What I normally do to avoid those errors is copy the raw json from a browser window to the clipboard and with a CS file open in Visual Studio do an Edit / Paste Special / Paste JSON as classes to automatically create the classes. After doing that I got the following that deserialized the data fine:
async Task Main()
{
await LookupMonsterStats("aboleth");
}
public async Task LookupMonsterStats(string name)
{
string monstersUri = "https://www.dnd5eapi.co/api/monsters/";
var formatted = name.Replace(" ", "-");
string apiResponse = string.Empty;
using (var httpClient = new HttpClient())
{
using (var response = await httpClient.GetAsync(monstersUri + formatted))
{
apiResponse = await response.Content.ReadAsStringAsync();
var monster = JsonConvert.DeserializeObject<Monster>(apiResponse);
monster.Dump();
}
}
}
public class Monster
{
public string index { get; set; }
public string name { get; set; }
public string size { get; set; }
public string type { get; set; }
public object subtype { get; set; }
public string alignment { get; set; }
public int armor_class { get; set; }
public int hit_points { get; set; }
public string hit_dice { get; set; }
public Speed speed { get; set; }
public int strength { get; set; }
public int dexterity { get; set; }
public int constitution { get; set; }
public int intelligence { get; set; }
public int wisdom { get; set; }
public int charisma { get; set; }
public Proficiency[] proficiencies { get; set; }
public object[] damage_vulnerabilities { get; set; }
public object[] damage_resistances { get; set; }
public object[] damage_immunities { get; set; }
public object[] condition_immunities { get; set; }
public Senses senses { get; set; }
public string languages { get; set; }
public int challenge_rating { get; set; }
public int xp { get; set; }
public Special_Abilities[] special_abilities { get; set; }
public Action[] actions { get; set; }
public Legendary_Actions[] legendary_actions { get; set; }
public string url { get; set; }
}
public class Speed
{
public string walk { get; set; }
public string swim { get; set; }
}
public class Senses
{
public string darkvision { get; set; }
public int passive_perception { get; set; }
}
public class Proficiency
{
public Proficiency1 proficiency { get; set; }
public int value { get; set; }
}
public class Proficiency1
{
public string index { get; set; }
public string name { get; set; }
public string url { get; set; }
}
public class Special_Abilities
{
public string name { get; set; }
public string desc { get; set; }
public Dc dc { get; set; }
}
public class Dc
{
public Dc_Type dc_type { get; set; }
public int dc_value { get; set; }
public string success_type { get; set; }
}
public class Dc_Type
{
public string index { get; set; }
public string name { get; set; }
public string url { get; set; }
}
public class Action
{
public string name { get; set; }
public string desc { get; set; }
public Options options { get; set; }
public Damage[] damage { get; set; }
public int attack_bonus { get; set; }
public Dc1 dc { get; set; }
public Usage usage { get; set; }
}
public class Options
{
public int choose { get; set; }
public From[][] from { get; set; }
}
public class From
{
public string name { get; set; }
public int count { get; set; }
public string type { get; set; }
}
public class Dc1
{
public Dc_Type1 dc_type { get; set; }
public int dc_value { get; set; }
public string success_type { get; set; }
}
public class Dc_Type1
{
public string index { get; set; }
public string name { get; set; }
public string url { get; set; }
}
public class Usage
{
public string type { get; set; }
public int times { get; set; }
}
public class Damage
{
public Damage_Type damage_type { get; set; }
public string damage_dice { get; set; }
}
public class Damage_Type
{
public string index { get; set; }
public string name { get; set; }
public string url { get; set; }
}
public class Legendary_Actions
{
public string name { get; set; }
public string desc { get; set; }
public int attack_bonus { get; set; }
public Damage1[] damage { get; set; }
}
public class Damage1
{
public Damage_Type1 damage_type { get; set; }
public string damage_dice { get; set; }
}
public class Damage_Type1
{
public string index { get; set; }
public string name { get; set; }
public string url { get; set; }
}

C# Newtonsoft deserialize JSON array and sometimes no array

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

C# Get Json Response into an Array

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

Newtonsoft.Json empty object after deserialization

I'm trying to deserialize JSON from a url using the following code. I'm getting an empty object even though I'm downloading a valid JSON string.
public static void tryjson() {
string json = new WebClient().DownloadString("http://www.sofascore.com/football/livescore/json");
SportItem sportItem = JsonConvert.DeserializeObject<SportItem>(json);
}
Classes:
public class Sport {
public int id { get; set; }
public string name { get; set; }
public string slug { get; set; }
}
public class Tournament2 {
public int id { get; set; }
public string name { get; set; }
public string slug { get; set; }
public int priority { get; set; }
public int order { get; set; }
public int uniqueId { get; set; }
public string uniqueName { get; set; }
}
public class Category {
public int id { get; set; }
public string name { get; set; }
public string slug { get; set; }
public int priority { get; set; }
public List<object> mcc { get; set; }
public string flag { get; set; }
}
public class Season {
public int id { get; set; }
public string name { get; set; }
public string slug { get; set; }
public string year { get; set; }
}
public class HomeScore {
public int current { get; set; }
public int period1 { get; set; }
public int normaltime { get; set; }
public int? aggregated { get; set; }
public int? penalties { get; set; }
public int? overtime { get; set; }
}
public class AwayScore {
public int current { get; set; }
public int period1 { get; set; }
public int normaltime { get; set; }
public int? aggregated { get; set; }
public int? penalties { get; set; }
public int? overtime { get; set; }
}
public class Status {
public int code { get; set; }
public string type { get; set; }
}
public class Changes {
public string changeDate { get; set; }
public List<object> changes { get; set; }
public int changeTimestamp { get; set; }
public bool hasExpired { get; set; }
public bool hasHomeChanges { get; set; }
public bool hasAwayChanges { get; set; }
}
public class RoundInfo {
public int round { get; set; }
public string name { get; set; }
}
public class Sport2 {
public int id { get; set; }
public string name { get; set; }
public string slug { get; set; }
}
public class HomeTeam {
public int id { get; set; }
public string name { get; set; }
public string slug { get; set; }
public string gender { get; set; }
public List<object> subTeams { get; set; }
}
public class AwayTeam {
public int id { get; set; }
public string name { get; set; }
public string slug { get; set; }
public string gender { get; set; }
public List<object> subTeams { get; set; }
}
public class Odds {
public int id { get; set; }
public double odds1 { get; set; }
public double oddsX { get; set; }
public double odds2 { get; set; }
public double odds1X { get; set; }
public double oddsX2 { get; set; }
public double odds12 { get; set; }
public double liveOdds1 { get; set; }
public double liveOddsX { get; set; }
public double liveOdds2 { get; set; }
public double liveOdds1X { get; set; }
public double liveOddsX2 { get; set; }
public double liveOdds12 { get; set; }
public string fractionalOdds1 { get; set; }
public string fractionalOddsX { get; set; }
public string fractionalOdds2 { get; set; }
public string fractionalOdds1X { get; set; }
public string fractionalOddsX2 { get; set; }
public string fractionalOdds12 { get; set; }
public string liveFractionalOdds1 { get; set; }
public string liveFractionalOddsX { get; set; }
public string liveFractionalOdds2 { get; set; }
public string liveFractionalOdds1X { get; set; }
public string liveFractionalOddsX2 { get; set; }
public string liveFractionalOdds12 { get; set; }
public string americanOdds1 { get; set; }
public string americanOddsX { get; set; }
public string americanOdds2 { get; set; }
public string americanOdds1X { get; set; }
public string americanOddsX2 { get; set; }
public string americanOdds12 { get; set; }
public string liveAmericanOdds1 { get; set; }
public string liveAmericanOddsX { get; set; }
public string liveAmericanOdds2 { get; set; }
public string liveAmericanOdds1X { get; set; }
public string liveAmericanOddsX2 { get; set; }
public string liveAmericanOdds12 { get; set; }
public int odds1Change { get; set; }
public int oddsXChange { get; set; }
public int odds2Change { get; set; }
public int odds1XChange { get; set; }
public int oddsX2Change { get; set; }
public int odds12Change { get; set; }
public string bet365OddsId1 { get; set; }
public string bet365OddsIdX { get; set; }
public string bet365OddsId2 { get; set; }
public string bet365OddsId1X { get; set; }
public string bet365OddsIdX2 { get; set; }
public string bet365OddsId12 { get; set; }
public string betSlipLink1 { get; set; }
public string betSlipLinkX { get; set; }
public string betSlipLink2 { get; set; }
public string betSlipLink1X { get; set; }
public string betSlipLinkX2 { get; set; }
public string betSlipLink12 { get; set; }
public bool liveOddsEnabled { get; set; }
public bool liveDoubleChanceOddsEnabled { get; set; }
}
public class Event {
public int id { get; set; }
public string customId { get; set; }
public HomeScore homeScore { get; set; }
public AwayScore awayScore { get; set; }
public Status status { get; set; }
public int winnerCode { get; set; }
public Changes changes { get; set; }
public RoundInfo roundInfo { get; set; }
public Sport2 sport { get; set; }
public HomeTeam homeTeam { get; set; }
public AwayTeam awayTeam { get; set; }
public Odds odds { get; set; }
public bool hasHighlights { get; set; }
public bool hasHighlightsStream { get; set; }
public bool hasEventPlayerStatistics { get; set; }
public bool hasEventPlayerHeatMap { get; set; }
public int rowCount { get; set; }
public int homeRedCards { get; set; }
public int awayRedCards { get; set; }
public string statusDescription { get; set; }
public bool hasLiveForm { get; set; }
public string name { get; set; }
public string startTime { get; set; }
public string formatedStartDate { get; set; }
public int startTimestamp { get; set; }
public string slug { get; set; }
public bool hasLineupsList { get; set; }
public bool hasOdds { get; set; }
public bool hasLiveOdds { get; set; }
public bool hasFirstToServe { get; set; }
public bool hasDraw { get; set; }
public bool isSyncable { get; set; }
public int? aggregatedWinnerCode { get; set; }
}
public class Tournament {
public Tournament2 tournament { get; set; }
public Category category { get; set; }
public Season season { get; set; }
public bool hasEventPlayerStatistics { get; set; }
public bool hasEventPlayerHeatMap { get; set; }
public List<Event> events { get; set; }
}
public class SportItem {
public Sport sport { get; set; }
public int rows { get; set; }
public List<Tournament> tournaments { get; set; }
}
public class Params {
public string sport { get; set; }
public object category { get; set; }
public string date { get; set; }
}
public class RootObject {
public SportItem sportItem { get; set; }
public Params #params { get; set; }
public bool isShortDate { get; set; }
}
What am I doing wrong?
Try this:
System.Net.WebClient wc = new System.Net.WebClient();
wc.DownloadStringCompleted += (s, u) =>
{
DownloadStringCompleted(s, u);
};
wc.DownloadStringAsync(new Uri("http://www.sofascore.com/football/livescore/json"));
private void DownloadStringCompleted(object s, DownloadStringCompletedEventArgs u)
{
try
{
var Item = JsonConvert.DeserializeObject<RootObject>(u.Result.ToString());
}
catch (Exception ex)
{ }
}
It looks like you need to parse into the json object first. Example:-
var data = (JObject)JsonConvert.DeserializeObject(resultJson);

Get converter value {null} from path 'track[40].like_count?

An exception of type
'Newtonsoft.Json.JsonSerializationException' occurred in
Newtonsoft.Json.DLL but was not handled in user code
Additional information: Error converting value {null} to type
'System.Boolean'. Path 'collection[8].downloadable', line 1, position
22866.
or
converter value {null} from path 'track[40].like_count
?
I use Json. How to fix it?
public class User
{
public string full_name { get; set; }
public string country { get; set; }
public string city { get; set; }
public int tracks_count { get; set; }
public int followers_count { get; set; }
public int followings_count { get; set; }
public int public_favorites_count { get; set; }
public int groups_count { get; set; }
public string description { get; set; }
public string plan { get; set; }
public int id { get; set; }
public string uri { get; set; }
public string username { get; set; }
public string kind { get; set; }
public string permalink { get; set; }
public string permalink_url { get; set; }
public string first_name { get; set; }
public string avatar_url { get; set; }
public string last_modified { get; set; }
}
public class __invalid_type__0
{
public string urn { get; set; }
public int entry_time { get; set; }
public string visual_url { get; set; }
public object link { get; set; }
}
public class Visuals2
{
public __invalid_type__0 __invalid_name__0 { get; set; }
}
public class Visuals
{
public string urn { get; set; }
public bool enabled { get; set; }
public Visuals2 visuals { get; set; }
public object tracking { get; set; }
}
public class Collection
{
public User user { get; set; }
public int user_id { get; set; }
public string genre { get; set; }
public string tag_list { get; set; }
public int duration { get; set; }
public bool downloadable { get; set; }
public bool streamable { get; set; }
public int original_content_size { get; set; }
public bool commentable { get; set; }
public string sharing { get; set; }
public bool #public { get; set; }
public string created_at { get; set; }
public string updated_at { get; set; }
public string isrc { get; set; }
public string state { get; set; }
public bool embeddable { get; set; }
public string embeddable_by { get; set; }
public string license { get; set; }
public string waveform_url { get; set; }
public bool feedable { get; set; }
public string label_name { get; set; }
public string release_date { get; set; }
public bool has_downloads_left { get; set; }
public string purchase_title { get; set; }
public string purchase_url { get; set; }
public string policy { get; set; }
public string monetization_model { get; set; }
public Visuals visuals { get; set; }
public string permalink { get; set; }
public string title { get; set; }
public string description { get; set; }
public string track_type { get; set; }
public string last_modified { get; set; }
public string artwork_url { get; set; }
public int id { get; set; }
public string kind { get; set; }
public int comment_count { get; set; }
public int download_count { get; set; }
public string uri { get; set; }
public string stream_url { get; set; }
public int playback_count { get; set; }
public string download_url { get; set; }
public object secret_token { get; set; }
public int reposts_count { get; set; }
public string permalink_url { get; set; }
public int likes_count { get; set; }
}
public class Facet2
{
public string filter { get; set; }
public int count { get; set; }
public string value { get; set; }
}
public class Facet
{
public string name { get; set; }
public List<Facet2> facets { get; set; }
}
public class RootObject
{
public List<Collection> collection { get; set; }
public List<Facet> facets { get; set; }
public int total_results { get; set; }
public string qid { get; set; }
public string query_urn { get; set; }
public string next_href { get; set; }
}

Categories