Trying best how to take the following classes and deserialize a Json file to return each class values back to Simpl+. I am able to receive the Total value but anything in a list I am at a lost.
public class Client
{
public string clientId { get; set; }
public string locale { get; set; }
public string location { get; set; }
public string auxiliaryId { get; set; }
public string description { get; set; }
public string type { get; set; }
public string typeDescription { get; set; }
public Hardware hardware { get; set; }
public Network network { get; set; }
}
public class Hardware
{
public string type { get; set; }
public string softwareVersion { get; set; }
public string serialNumber { get; set; }
public string hardwareVersion { get; set; }
public string model { get; set; }
}
public class Network
{
public string ip { get; set; }
public string mac { get; set; }
public object homepage { get; set; }
public string dhcpSubnet { get; set; }
}
public class Result
{
public List<Client> clients { get; set; }
public string total { get; set; }
public int limit { get; set; }
public int page { get; set; }
}
public class Root
{
public string jsonrpc { get; set; }
public object id { get; set; }
public Result result { get; set; }
}
I was able to resolve this by adding the following to the foreach statement:
args.MyIndex = (ushort)(rootObject.TriplePlayResult.clients.IndexOf(item) + 1);
I'm not able to get the value from OneDay.price_change. The HTTP response is OK and I'm getting the following:
HTTP Response
"[{\"id\":\"BTC\",\"currency\":\"BTC\",\"symbol\":\"BTC\",\"name\":\"Bitcoin\",\"logo_url\":\"https://s3.us-east-2.amazonaws.com/nomics-api/static/images/currencies/btc.svg\",\"status\":\"active\",\"price\":\"60947.08258854\",\"price_date\":\"2021-10-31T00:00:00Z\",\"price_timestamp\":\"2021-10-31T18:51:00Z\",\"circulating_supply\":\"18860037\",\"max_supply\":\"21000000\",\"market_cap\":\"1149464232662\",\"market_cap_dominance\":\"0.4078\",\"num_exchanges\":\"397\",\"num_pairs\":\"67587\",\"num_pairs_unmapped\":\"5196\",\"first_candle\":\"2011-08-18T00:00:00Z\",\"first_trade\":\"2011-08-18T00:00:00Z\",\"first_order_book\":\"2017-01-06T00:00:00Z\",\"rank\":\"1\",\"high\":\"66082.82561618\",\"high_timestamp\":\"2021-10-20T00:00:00Z\",\"1h\":{\"volume\":\"1248590564.91\",\"price_change\":\"-85.32656234\",\"price_change_pct\":\"-0.0014\",\"volume_change\":\"-218879322.04\",\"volume_change_pct\":\"-0.1492\",\"market_cap_change\":\"-1607003923.65\",\"market_cap_change_pct\":\"-0.0014\"},\"1d\":{\"volume\":\"39937857069.60\",\"price_change\":\"-845.68642611\",\"price_change_pct\":\"-0.0137\",\"volume_change\":\"1918883279.43\",\"volume_change_pct\":\"0.0505\",\"market_cap_change\":\"-15892518975.54\",\"market_cap_change_pct\":\"-0.0136\"}}]\n"
However, for some reason, I'm not able to take the 1d price change. I'm not sure what could be the problem. Any help is appreciated!
Model:
public class OneHour
{
public string Volume { get; set; }
public string Price_change { get; set; }
public string Price_change_pct { get; set; }
public string Volume_change { get; set; }
public string Volume_change_pct { get; set; }
public string Market_cap_change { get; set; }
public string Market_cap_change_pct { get; set; }
}
public class OneDay
{
public string Volume { get; set; }
public string Price_change { get; set; }
public string Price_change_pct { get; set; }
public string Volume_change { get; set; }
public string Volume_change_pct { get; set; }
public string Market_cap_change { get; set; }
public string Market_cap_change_pct { get; set; }
}
public class CryptoApiMain
{
public OneHour OneHour { get; set; }
public OneDay OneDay { get; set; }
public string Id { get; set; }
public string Symbol { get; set; }
public string Status { get; set; }
public double Price { get; set; }
public string Price_date { get; set; }
public string Circulating_supply { get; set; }
public string Num_exchanges { get; set; }
public string Num_pairs { get; set; }
public string Rank { get; set; }
public string High { get; set; }
}
var theresponse = settingsService.CryptoApiResult(cryptoStock).Result;
foreach (var rez in theresponse)
{
<span id="stockSymbolCrypto">#cryptoStock</span>
<p>$#Convert.ToInt64(#rez.Price) #rez.OneDay.Price_change</p>
}
#rez.OneDay.Price_change error popup
Problem is that your property name in json (1d) and property name in c# model (OneDay) is not matching.
Use the below if you are using System.Text.Json (.Net Core 3.0 and newer)
[JsonPropertyName("1d")]
public OneDay OneDay { get; set; }
Use the below if you are using Newtonsoft (Before .Net Core 3.0)
[JsonProperty(PropertyName = "1d")]
public OneDay OneDay { get; set; }
Your " public OneHour OneHour { get; set; } " and " public OneDay OneDay { get; set; } " properties should be bind to [JsonProperty("1h")] and [JsonProperty("1d")]
try this
CryptoApiMain[] jsond = JsonConvert.DeserializeObject<CryptoApiMain[]>(json);
var price = jsond[0].OneDay.PriceChange;
result
-845.68642611
classes
public partial class CryptoApiMain
{
[JsonProperty("1h")]
public One OneHour { get; set; }
[JsonProperty("1d")]
public One OneDay { get; set; }
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("currency")]
public string Currency { get; set; }
[JsonProperty("symbol")]
public string Symbol { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("logo_url")]
public Uri LogoUrl { get; set; }
[JsonProperty("status")]
public string Status { get; set; }
[JsonProperty("price")]
public string Price { get; set; }
[JsonProperty("price_date")]
public DateTimeOffset PriceDate { get; set; }
[JsonProperty("price_timestamp")]
public DateTimeOffset PriceTimestamp { get; set; }
[JsonProperty("circulating_supply")]
public long CirculatingSupply { get; set; }
[JsonProperty("max_supply")]
public long MaxSupply { get; set; }
[JsonProperty("market_cap")]
public string MarketCap { get; set; }
[JsonProperty("market_cap_dominance")]
public string MarketCapDominance { get; set; }
[JsonProperty("num_exchanges")]
public long NumExchanges { get; set; }
[JsonProperty("num_pairs")]
public long NumPairs { get; set; }
[JsonProperty("num_pairs_unmapped")]
public long NumPairsUnmapped { get; set; }
[JsonProperty("first_candle")]
public DateTimeOffset FirstCandle { get; set; }
[JsonProperty("first_trade")]
public DateTimeOffset FirstTrade { get; set; }
[JsonProperty("first_order_book")]
public DateTimeOffset FirstOrderBook { get; set; }
[JsonProperty("rank")]
public long Rank { get; set; }
[JsonProperty("high")]
public string High { get; set; }
[JsonProperty("high_timestamp")]
public DateTimeOffset HighTimestamp { get; set; }
}
public partial class One
{
[JsonProperty("volume")]
public string Volume { get; set; }
[JsonProperty("price_change")]
public string PriceChange { get; set; }
[JsonProperty("price_change_pct")]
public string PriceChangePct { get; set; }
[JsonProperty("volume_change")]
public string VolumeChange { get; set; }
[JsonProperty("volume_change_pct")]
public string VolumeChangePct { get; set; }
[JsonProperty("market_cap_change")]
public string MarketCapChange { get; set; }
[JsonProperty("market_cap_change_pct")]
public string MarketCapChangePct { get; set; }
}
I deserialize complex JSON (Spotify Playlist) and get root level values but I cannot get branches values. I Google problem, try different options without success but, I assume its silly mistake or lack of knowledge so therefore just ask for help what I am missing?
My classes are:
public class Playlist
{
public string collaborative { get; set; }
public string description { get; set; }
//public <ExternalUrls> external_urls { get; set; } //object
//public List<Followers> followers { get; set; } //object
public string href { get; set; }
public string id { get; set; }
//public List<Image> images { get; set; } //array
public string name { get; set; }
}
public class Tracks
{
public string href { get; set; }
public Item items { get; set; } //object
public string limit { get; set; }
public string next { get; set; }
public string offset { get; set; }
public string previous { get; set; }
public string total { get; set; }
}
And code to deserialize looks like that:
StreamReader responseFromServer = new StreamReader(myWebResponse.GetResponseStream());
var dataResponse = responseFromServer.ReadToEnd();
responseFromServer.Close();
var elements = new JavaScriptSerializer().Deserialize<Playlist>(dataResponse);
RootBuffer.AddRow();
RootBuffer.collaborative = elements.collaborative.ToString();
foreach (Tracks trs in elements.tracks)
{
TracksBuffer.AddRow();
TracksBuffer.href = trs.href.ToString()
}
I genereated the classes using this excellent site: json2csharp.com
And used your existing deserialization code successfully with the following classes. It populated all the data including the child collections (brace yourself, it's a long one):
public class Playlist
{
public bool collaborative { get; set; }
public string description { get; set; }
public ExternalUrls external_urls { get; set; }
public Followers followers { get; set; }
public string href { get; set; }
public string id { get; set; }
public List<Image> images { get; set; }
public string name { get; set; }
public Owner owner { get; set; }
public bool #public { get; set; }
public string snapshot_id { get; set; }
public Tracks tracks { get; set; }
public string type { get; set; }
public string uri { get; set; }
}
public class ExternalUrls
{
public string spotify { get; set; }
}
public class Followers
{
public object href { get; set; }
public int total { get; set; }
}
public class Image
{
public object height { get; set; }
public string url { get; set; }
public object width { get; set; }
}
public class ExternalUrls2
{
public string spotify { get; set; }
}
public class Owner
{
public ExternalUrls2 external_urls { get; set; }
public string href { get; set; }
public string id { get; set; }
public string type { get; set; }
public string uri { get; set; }
}
public class ExternalUrls3
{
public string spotify { get; set; }
}
public class AddedBy
{
public ExternalUrls3 external_urls { get; set; }
public string href { get; set; }
public string id { get; set; }
public string type { get; set; }
public string uri { get; set; }
}
public class ExternalUrls4
{
public string spotify { get; set; }
}
public class Image2
{
public int height { get; set; }
public string url { get; set; }
public int width { get; set; }
}
public class Album
{
public string album_type { get; set; }
public List<object> available_markets { get; set; }
public ExternalUrls4 external_urls { get; set; }
public string href { get; set; }
public string id { get; set; }
public List<Image2> images { get; set; }
public string name { get; set; }
public string type { get; set; }
public string uri { get; set; }
}
public class ExternalUrls5
{
public string spotify { get; set; }
}
public class Artist
{
public ExternalUrls5 external_urls { get; set; }
public string href { get; set; }
public string id { get; set; }
public string name { get; set; }
public string type { get; set; }
public string uri { get; set; }
}
public class ExternalIds
{
public string isrc { get; set; }
}
public class ExternalUrls6
{
public string spotify { get; set; }
}
public class Track
{
public Album album { get; set; }
public List<Artist> artists { get; set; }
public List<object> available_markets { get; set; }
public int disc_number { get; set; }
public int duration_ms { get; set; }
public bool #explicit { get; set; }
public ExternalIds external_ids { get; set; }
public ExternalUrls6 external_urls { get; set; }
public string href { get; set; }
public string id { get; set; }
public string name { get; set; }
public int popularity { get; set; }
public string preview_url { get; set; }
public int track_number { get; set; }
public string type { get; set; }
public string uri { get; set; }
}
public class Item
{
public string added_at { get; set; }
public AddedBy added_by { get; set; }
public bool is_local { get; set; }
public Track track { get; set; }
}
public class Tracks
{
public string href { get; set; }
public List<Item> items { get; set; }
public int limit { get; set; }
public object next { get; set; }
public int offset { get; set; }
public object previous { get; set; }
public int total { get; set; }
}
Hope this helps.
I am getting the following exception when I try to deserialize a JSON response from Twitter API. It sometime went through but sometime have an issue.
Below are the classes:
public static List<Tweet> Newtwt = new List<Tweet>();
public class Url2
{
public string url { get; set; }
public string expanded_url { get; set; }
public string display_url { get; set; }
public List<int> indices { get; set; }
}
public class Url
{
public List<Url2> urls { get; set; }
}
public class Description
{
public List<object> urls { get; set; }
}
public class Entities
{
public Url url { get; set; }
public Description description { get; set; }
}
public class User
{
public int id { get; set; }
public string id_str { get; set; }
public string name { get; set; }
public string screen_name { get; set; }
public string location { get; set; }
public string description { get; set; }
public string url { get; set; }
public Entities entities { get; set; }
public bool #protected { get; set; }
public int followers_count { get; set; }
public int friends_count { get; set; }
public int listed_count { get; set; }
public string created_at { get; set; }
public int favourites_count { get; set; }
public int utc_offset { get; set; }
public string time_zone { get; set; }
public bool geo_enabled { get; set; }
public bool verified { get; set; }
public int statuses_count { get; set; }
public string lang { get; set; }
public bool contributors_enabled { get; set; }
public bool is_translator { get; set; }
public string profile_background_color { get; set; }
public string profile_background_image_url { get; set; }
public string profile_background_image_url_https { get; set; }
public bool profile_background_tile { get; set; }
public string profile_image_url { get; set; }
public string profile_image_url_https { get; set; }
public string profile_link_color { get; set; }
public string profile_sidebar_border_color { get; set; }
public string profile_sidebar_fill_color { get; set; }
public string profile_text_color { get; set; }
public bool profile_use_background_image { get; set; }
public bool default_profile { get; set; }
public bool default_profile_image { get; set; }
public object following { get; set; }
public bool follow_request_sent { get; set; }
public object notifications { get; set; }
}
public class Entities2
{
public List<object> hashtags { get; set; }
public List<object> symbols { get; set; }
public List<object> urls { get; set; }
public List<object> user_mentions { get; set; }
}
public class RootObject
{
public string created_at { get; set; }
public object id { get; set; }
public string id_str { get; set; }
public string text { get; set; }
public string source { get; set; }
public bool truncated { get; set; }
public object in_reply_to_status_id { get; set; }
public object in_reply_to_status_id_str { get; set; }
public object in_reply_to_user_id { get; set; }
public object in_reply_to_user_id_str { get; set; }
public object in_reply_to_screen_name { get; set; }
public User user { get; set; }
public object geo { get; set; }
public object coordinates { get; set; }
public object place { get; set; }
public object contributors { get; set; }
public int retweet_count { get; set; }
public int favorite_count { get; set; }
public Entities2 entities { get; set; }
public bool favorited { get; set; }
public bool retweeted { get; set; }
public string lang { get; set; }
public bool? possibly_sensitive { get; set; }
}
public class Tweet
{
public string UserName { get; set; }
[JsonProperty(PropertyName = "text")]
public string Message { get; set; }
[JsonProperty(PropertyName = "id")]
public object ID { get; set; }
[JsonProperty(PropertyName = "created_at")]
public DateTime TwitTime { get; set; }
}
And I try to deserialize the response in the following way:
string str = TwitterAPI(Request.QueryString["screen_name"].ToString(), "10");
var root = JsonConvert.DeserializeObject<List<RootObject>>(str);
Where TwitterAPI() will return the response from following Twitter API:
https://api.twitter.com/1.1/statuses/user_timeline.json
Below is the detailed error:
I just found an answer.
The issue was with the limitations of Twitter API as the documentation says:
"When an application exceeds the rate limit for a given API endpoint, the Twitter API will now return an HTTP 429 error"
and I was exceeding the limit so it was giving an exception (429) Too Many Requests.
If you hit the rate limit on a given endpoint, this is the body of the HTTP 429 message that you will see:
{
"errors": [
{
"code": 88,
"message": "Rate limit exceeded"
}
]
}
So it was returning only an error message in JSON format and it was passing it to Deserialize function which in turn giving that error.
Thanks all for your suggestions.
I'm getting the following exception when using this bit of code to deserialize a JSON response from CrunchBase. The weird thing is it only happens to certain pages that are being deserialized even though both the results that work fine and the ones that don't both have empty [], empty"", and null values in key:value pairs. How can I cast or correct my mistake?
Exception gets thrown here:
JsonSerializer serializer = new JsonSerializer();
RootObject ro = JsonConvert.DeserializeObject<RootObject>(response);
The inner exception is:
InnerException:
Message=Could not cast or convert from {null} to System.Int32.
Source=Newtonsoft.Json
Thanks for your eyes in advance!
Update:
as asked for the structure of the root object and the additional objects on that JSON endpoint. These were generated by http://json2csharp.com/ after putting the URL of the JSON endpoint into it.
The JSON is long so here are two example links: this one works without error http://api.crunchbase.com/v/1/company/kiip.js , while this other (and others) throws the exception http://api.crunchbase.com/v/1/company/tata-communications.js
public class Image
{
public List<List<object>> available_sizes { get; set; }
public object attribution { get; set; }
}
public class Person
{
public string first_name { get; set; }
public string last_name { get; set; }
public string permalink { get; set; }
}
public class Relationship
{
public bool is_past { get; set; }
public string title { get; set; }
public Person person { get; set; }
}
public class Provider
{
public string name { get; set; }
public string permalink { get; set; }
}
public class Providership
{
public string title { get; set; }
public bool is_past { get; set; }
public Provider provider { get; set; }
}
public class FinancialOrg
{
public string name { get; set; }
public string permalink { get; set; }
}
public class Person2
{
public string first_name { get; set; }
public string last_name { get; set; }
public string permalink { get; set; }
}
public class Investment
{
public object company { get; set; }
public FinancialOrg financial_org { get; set; }
public Person2 person { get; set; }
}
public class FundingRound
{
public string round_code { get; set; }
public string source_url { get; set; }
public string source_description { get; set; }
public double raised_amount { get; set; }
public string raised_currency_code { get; set; }
public int funded_year { get; set; }
public int funded_month { get; set; }
public int funded_day { get; set; }
public List<Investment> investments { get; set; }
}
public class Office
{
public string description { get; set; }
public string address1 { get; set; }
public string address2 { get; set; }
public string zip_code { get; set; }
public string city { get; set; }
public string state_code { get; set; }
public string country_code { get; set; }
public object latitude { get; set; }
public object longitude { get; set; }
}
public class VideoEmbed
{
public string embed_code { get; set; }
public string description { get; set; }
}
public class Screenshot
{
public List<List<object>> available_sizes { get; set; }
public object attribution { get; set; }
}
public class RootObject
{
public string name { get; set; }
public string permalink { get; set; }
public string crunchbase_url { get; set; }
public string homepage_url { get; set; }
public string blog_url { get; set; }
public string blog_feed_url { get; set; }
public string twitter_username { get; set; }
public string category_code { get; set; }
public int number_of_employees { get; set; }
public int founded_year { get; set; }
public int founded_month { get; set; }
public object founded_day { get; set; }
public object deadpooled_year { get; set; }
public object deadpooled_month { get; set; }
public object deadpooled_day { get; set; }
public object deadpooled_url { get; set; }
public string tag_list { get; set; }
public string alias_list { get; set; }
public string email_address { get; set; }
public string phone_number { get; set; }
public string description { get; set; }
public string created_at { get; set; }
public string updated_at { get; set; }
public string overview { get; set; }
public Image image { get; set; }
public List<object> products { get; set; }
public List<Relationship> relationships { get; set; }
public List<object> competitions { get; set; }
public List<Providership> providerships { get; set; }
public string total_money_raised { get; set; }
public List<FundingRound> funding_rounds { get; set; }
public List<object> investments { get; set; }
public object acquisition { get; set; }
public List<object> acquisitions { get; set; }
public List<Office> offices { get; set; }
public List<object> milestones { get; set; }
public object ipo { get; set; }
public List<VideoEmbed> video_embeds { get; set; }
public List<Screenshot> screenshots { get; set; }
public List<object> external_links { get; set; }
}
Json.NET supports JSON Schema. You could create a schema with all the required properties marked and validate incoming JSON against it before deserializing. In this you can check if value is null you can make change it to some default value.
Hope this works for you.