Crestron Deserialize in C# and send array to Simpl+ - c#

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

Related

Got stuck at deserializing a JSON web response

I have some problems deserializing the following JSON string. On all of my other responses it works really good but not for this one. I tried so many different things and I checked the Stream class about 100 times. I also have used a generated class from json2csharp but all my deserialized Data is NULL.
My code to get the response:
public Stream getStream(string userID)
{
var request = GetRequest("streams/{channelID}", Method.GET);
request.AddUrlSegment("channelID", userID);
var response = restClient.Execute<Stream>(request);
return response.Data;
}
response.Content shows me as example something like that:
{
"stream":
{
"_id":25649270464,
"game":"test",
"broadcast_platform":"other",
"community_id":"xxxxxxxxx",
"community_ids":["xxxxxx"],
"viewers":2421,
"video_height":1080,
"average_fps":61.7876424715,
"delay":0,
"created_at":"2017-07-02T10:01:28Z",
"is_playlist":false,
"stream_type":"live",
"preview":
{
"small":"https://static-cdn.jtvnw.net/previews-ttv/live_user_lostaiming-80x45.jpg",
"medium":"https://static-cdn.jtvnw.net/previews-ttv/live_user_lostaiming-320x180.jpg",
"large":"https://static-cdn.jtvnw.net/previews-ttv/live_user_lostaiming-640x360.jpg",
"template":"https://static-cdn.jtvnw.net/previews-ttv/live_user_lostaiming-{width}x{height}.jpg"
},
"channel":
{
"mature":false,
"status":"Test"
,"broadcaster_language":"de",
"display_name":"LOSTAIMING",
"game":"test",
"language":"en",
"_id":44281267,
"name":"lostaiming",
"created_at":"2013-06-02T16:42:19.329009Z",
"updated_at":"2017-07-02T13:05:11.555285Z",
"partner":true,
"logo":"https://static-cdn.jtvnw.net/jtv_user_pictures/lostaiming-profile_image-e9d7ea0893748d6a-300x300.png",
"video_banner":"https://static-cdn.jtvnw.net/jtv_user_pictures/cc34c6b909a435ae-channel_offline_image-1920x1080.png",
"profile_banner":"https://static-cdn.jtvnw.net/jtv_user_pictures/c187e8871c0f6a2b-profile_banner-480.png",
"profile_banner_background_color":"",
"url":"https://www.twitch.tv/lostaiming",
"views":2292173,
"followers":55672,
"broadcaster_type":"",
"description":"Blubb"
}
}
}
And my Stream class looks like this:
class Stream
{
[JsonProperty("stream")]
public SubStream stream { get; set; }
}
class SubStream
{
[JsonProperty("_id")]
public string ID { get; set; }
[JsonProperty("game")]
public string Game { get; set; }
[JsonProperty("broadcast_platform")]
public string BroadcastPlatform { get; set; }
[JsonProperty("community_id")]
public string CommunityID { get; set; }
[JsonProperty("community_ids")]
public List<object> CommunityIDS { get; set; }
[JsonProperty("viewers")]
public long Viewers { get; set; }
[JsonProperty("video_height")]
public long VideoHeigt { get; set; }
[JsonProperty("average_fps")]
public double AverageFps { get; set; }
[JsonProperty("delay")]
public long Delay { get; set; }
[JsonProperty("createt_at")]
public DateTime CreatetAt { get; set; }
[JsonProperty("is_playlist")]
public bool IsPlaylist { get; set; }
[JsonProperty("stream_type")]
public string StreamType { get; set; }
[JsonProperty("preview")]
public StreamPreview Preview { get; set; }
[JsonProperty("channel")]
public Channel channel { get; set; }
}
class StreamPreview
{
[JsonProperty("small")]
public string SmallPreview { get; set; }
[JsonProperty("medium")]
public string MediumPreview { get; set; }
[JsonProperty("large")]
public string LargPreview { get; set; }
[JsonProperty("template")]
public string TemplatePreview { get; set; }
}
public class Channel
{
[JsonProperty("mature")]
public bool Mature { get; set; }
[JsonProperty("status")]
public string Status { get; set; }
[JsonProperty("broadcaster_language")]
public string BroadcasterLanguage { get; set; }
[JsonProperty("display_name")]
public string DisplayName { get; set; }
[JsonProperty("game")]
public string Game { get; set; }
[JsonProperty("language")]
public string Language { get; set; }
[JsonProperty("_id")]
public string ID { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("created_at")]
public DateTime CreatedAt { get; set; }
[JsonProperty("updated_at")]
public DateTime UpdatedAt { get; set; }
[JsonProperty("partner")]
public bool Partner { get; set; }
[JsonProperty("logo")]
public string Logo { get; set; }
[JsonProperty("video_banner")]
public string VideoBanner { get; set; }
[JsonProperty("profile_banner")]
public string ProfileBanner { get; set; }
[JsonProperty("profile_banner_background_color")]
public string ProfileBannerBackgroundColor { get; set; }
[JsonProperty("url")]
public string Url { get; set; }
[JsonProperty("views")]
public long Views { get; set; }
[JsonProperty("followers")]
public long Followers { get; set; }
[JsonProperty("broadcaster_type")]
public string BroadcastType { get; set; }
[JsonProperty("stream_key")]
public string StreamKey { get; set; }
[JsonProperty("email")]
public string Email { get; set; }
}
1) use JSON Utils (https://jsonutils.com/) to generate your C# classes (for attributes select JsonProperty)
2) Newtonsoft.Json is pretty much the standard best library to work with JSON formats in .NET, you can get it from nuget.
3) The code should look something like this, and deserialization should work without any problems:
class Program
{
private static void Main(string[] args)
{
var myObj = JsonConvert.DeserializeObject<JsonDef>(json);
Console.Read();
}
}
public class Preview
{
[JsonProperty("small")]
public string small { get; set; }
[JsonProperty("medium")]
public string medium { get; set; }
[JsonProperty("large")]
public string large { get; set; }
[JsonProperty("template")]
public string template { get; set; }
}
public class Channel
{
[JsonProperty("mature")]
public bool mature { get; set; }
[JsonProperty("status")]
public string status { get; set; }
[JsonProperty("broadcaster_language")]
public string broadcaster_language { get; set; }
[JsonProperty("display_name")]
public string display_name { get; set; }
[JsonProperty("game")]
public string game { get; set; }
[JsonProperty("language")]
public string language { get; set; }
[JsonProperty("_id")]
public int _id { get; set; }
[JsonProperty("name")]
public string name { get; set; }
[JsonProperty("created_at")]
public DateTime created_at { get; set; }
[JsonProperty("updated_at")]
public DateTime updated_at { get; set; }
[JsonProperty("partner")]
public bool partner { get; set; }
[JsonProperty("logo")]
public string logo { get; set; }
[JsonProperty("video_banner")]
public string video_banner { get; set; }
[JsonProperty("profile_banner")]
public string profile_banner { get; set; }
[JsonProperty("profile_banner_background_color")]
public string profile_banner_background_color { get; set; }
[JsonProperty("url")]
public string url { get; set; }
[JsonProperty("views")]
public int views { get; set; }
[JsonProperty("followers")]
public int followers { get; set; }
[JsonProperty("broadcaster_type")]
public string broadcaster_type { get; set; }
[JsonProperty("description")]
public string description { get; set; }
}
public class Stream
{
[JsonProperty("_id")]
public long _id { get; set; }
[JsonProperty("game")]
public string game { get; set; }
[JsonProperty("broadcast_platform")]
public string broadcast_platform { get; set; }
[JsonProperty("community_id")]
public string community_id { get; set; }
[JsonProperty("community_ids")]
public IList<string> community_ids { get; set; }
[JsonProperty("viewers")]
public int viewers { get; set; }
[JsonProperty("video_height")]
public int video_height { get; set; }
[JsonProperty("average_fps")]
public double average_fps { get; set; }
[JsonProperty("delay")]
public int delay { get; set; }
[JsonProperty("created_at")]
public DateTime created_at { get; set; }
[JsonProperty("is_playlist")]
public bool is_playlist { get; set; }
[JsonProperty("stream_type")]
public string stream_type { get; set; }
[JsonProperty("preview")]
public Preview preview { get; set; }
[JsonProperty("channel")]
public Channel channel { get; set; }
}
public class JsonDef
{
[JsonProperty("stream")]
public Stream stream { get; set; }
}
It's because of the DateTime format of the JSON. It is not in a well-formed .Net DateTime. so you can get it as a string and then convert it the way you want or change its format into a readable .Net one.

JsonConvert.DeserializeObject not working sometimes

I'm trying to Deserialize some json using JsonConver.DeserializeObject. however it's not working on some json from the api I'm using. here is a link that does not work: https://api.pokemontcg.io/v1/cards?setCode=smp
and here is a link that does work. https://api.pokemontcg.io/v1/cards?setCode=sm2
I'm not sure why it sometimes works and sometimes not. The data that comes out of it is very similar to each other, just different cards.
Here is the code:
public static async Task<T> GetDataAsync<T>(this HttpClient client, string address, string querystring)
where T : class
{
var uri = address;
if (!string.IsNullOrEmpty(querystring))
{
uri += querystring;
}
var httpMessage = await client.GetStringAsync(uri);
var jsonObject = JsonConvert.DeserializeObject<T>(httpMessage);
return jsonObject;
}
Now my card class
namespace CardAppReal.Lib.Models
{
public class Card
{
public string id { get; set; }
public string name { get; set; }
public string imageUrl { get; set; }
public string imageUrlHiRes { get; set; }
public string supertype { get; set; } // if pokemon, trainer or energy
public string setcode { get; set; }
public int number { get; set; }
public string set { get; set; }
}
}
With a root
using System.Collections.Generic;
using CardAppReal.Lib.Models;
namespace CardAppReal.Lib.Entities
{
public class RootCard
{
public List<Card> cards { get; set; }
}
}
If u could help me out I would find it amazing.
I have tested your json.
this is the Model
namespace Test
{
public class Attack
{
public List<string> cost { get; set; }
public string name { get; set; }
public string text { get; set; }
public string damage { get; set; }
public int convertedEnergyCost { get; set; }
}
public class Weakness
{
public string type { get; set; }
public string value { get; set; }
}
public class Resistance
{
public string type { get; set; }
public string value { get; set; }
}
public class Ability
{
public string name { get; set; }
public string text { get; set; }
public string type { get; set; }
}
public class Card
{
public string id { get; set; }
public string name { get; set; }
public int nationalPokedexNumber { get; set; }
public string imageUrl { get; set; }
public string imageUrlHiRes { get; set; }
public string subtype { get; set; }
public string supertype { get; set; }
public string hp { get; set; }
public List<string> retreatCost { get; set; }
public string number { get; set; }
public string artist { get; set; }
public string rarity { get; set; }
public string series { get; set; }
public string set { get; set; }
public string setCode { get; set; }
public List<string> types { get; set; }
public List<Attack> attacks { get; set; }
public List<Weakness> weaknesses { get; set; }
public List<Resistance> resistances { get; set; }
public string evolvesFrom { get; set; }
public Ability ability { get; set; }
public List<string> text { get; set; }
}
public class RootObject
{
public List<Card> cards { get; set; }
}
}
And this is how I call the Deserialize
RootObject root = Newtonsoft.Json.JsonConvert.DeserializeObject<RootObject>(RootObject.WRONG_JSON);
(NB WRONG_JSON is your json string...)

PHP error with multiple levels of key-value JSON pairs

I am using multiple levels of JSON data coming into php from a C# application, as in:
public class User_Group
{
public int ID_UserGroup { get; set; }
public string Name_UserGroup { get; set; }
public int UserID { get; set; }
}
public class User_Role
{
public int ID_User { get; set; }
public string Role_User { get; set; }
public string User_Role_Description { get; set; }
public List<User_Group> UserGroup { get; set; }
}
public class Stand_Orte
{
public int ID { get; set; }
public string Bezeichnung { get; set; }
public List<Modul> modul { get; set; }
}
public class Modul
{
public string ID { get; set; }
public string Seriennummer { get; set; }
public string Bezeichnung { get; set; }
public string StandortID { get; set; }
public List<Mess_Kanal> MessKanal { get; set; }
}
public class Mess_Kanal
{
public string ID { get; set; }
public string ModulID { get; set; }
public List<LogMess_Daten> LogMessDaten { get; set; }
}
public class LogMess_Daten
{
public string KanalID { get; set; }
public string Zeitstempel { get; set; }
}
public class RootObject
{
public int ID_Project { get; set; }
public string Name_Project { get; set; }
public int Receiver_ID { get; set; }
public string Receiver_Name { get; set; }
public int UserID { get; set; }
public User_Role UserRole { get; set; }
public Stand_Orte Standorte { get; set; }
}
I have an issue with accessing the 3rd level data elements.
For Eg., I am able to get the values uptil Project-> Stand_Orte-> Modul. but after that Project-> Stand_Orte-> Modul-> MessKanal Throws an error in PHP as " Trying to get property of non-object ".
I tried the following:
$phpArray['project']->Standorte[0]->modul[0]->MessKanal[0]->ID
$messkanals=$phpArray->Standorte->modul->MessKanal;
And then used a "foreach ($messkanals as $messkanal)" to insert MessKanal data into MYSQL.
it gives me the following errors respectively.
Cannot use object of type stdClass as array
Trying to get property of non-object
does anyone have any idea?
Thanks,
Revathy

Could not cast or convert from System.Int64 to System.Collections.Generic.List

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.

Could not cast or convert from {null} to system.Int32 in JSON response C#

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.

Categories

Resources