I am new to JSON and I need to get selected values out of a JSON response.this is my code below please help me i use narrativa covid19 api
https://api.covid19tracking.narrativa.com/api/2020-03-22/country/:countryname "
var client = new RestClient("https://api.covid19tracking.narrativa.com/api/2020-03-22/country/" + "us");
client.Timeout = -1;
var request = new RestRequest(Method.GET);
IRestResponse response = client.Execute(request);
Debug.Log(response.Content);
string jsonStringDet = responseCountries.Content;
Rootobject myDeserializedClass = JsonConvert.DeserializeObject<Rootobject>(jsonStringDet);
and this is my class i use past special to get this class on visula studio from this link
https://api.covid19tracking.narrativa.com/api/2020-11-02/country/us
public class Rootobject
{
public Dates dates { get; set; }
public Metadata metadata { get; set; }
public Total total { get; set; }
public string updated_at { get; set; }
}
public class Dates
{
public _20201102 _20201102 { get; set; }
}
public class _20201102
{
public Countries countries { get; set; }
public Info info { get; set; }
}
public class Countries
{
public US US { get; set; }
}
public class US
{
public string date { get; set; }
public string id { get; set; }
public Link[] links { get; set; }
public string name { get; set; }
public string name_es { get; set; }
public string name_it { get; set; }
public Region[] regions { get; set; }
public string source { get; set; }
public int today_confirmed { get; set; }
public int today_deaths { get; set; }
public int today_new_confirmed { get; set; }
public int today_new_deaths { get; set; }
public int today_new_open_cases { get; set; }
public int today_new_recovered { get; set; }
public int today_open_cases { get; set; }
public int today_recovered { get; set; }
public float today_vs_yesterday_confirmed { get; set; }
public float today_vs_yesterday_deaths { get; set; }
public float today_vs_yesterday_open_cases { get; set; }
public float today_vs_yesterday_recovered { get; set; }
public int yesterday_confirmed { get; set; }
public int yesterday_deaths { get; set; }
public int yesterday_open_cases { get; set; }
public int yesterday_recovered { get; set; }
}
public class Link
{
public string href { get; set; }
public string rel { get; set; }
public string type { get; set; }
}
public class Region
{
public string date { get; set; }
public string id { get; set; }
public Link1[] links { get; set; }
public string name { get; set; }
public string name_es { get; set; }
public string name_it { get; set; }
public string source { get; set; }
public Sub_Regions[] sub_regions { get; set; }
public int today_confirmed { get; set; }
public int today_deaths { get; set; }
public int today_new_confirmed { get; set; }
public int today_new_deaths { get; set; }
public int today_new_open_cases { get; set; }
public int today_new_recovered { get; set; }
public int today_new_tests { get; set; }
public int today_new_total_hospitalised_patients { get; set; }
public int today_open_cases { get; set; }
public int today_recovered { get; set; }
public int today_tests { get; set; }
public int today_total_hospitalised_patients { get; set; }
public float? today_vs_yesterday_confirmed { get; set; }
public float? today_vs_yesterday_deaths { get; set; }
public float today_vs_yesterday_open_cases { get; set; }
public float? today_vs_yesterday_recovered { get; set; }
public float today_vs_yesterday_tests { get; set; }
public float? today_vs_yesterday_total_hospitalised_patients { get; set; }
public int yesterday_confirmed { get; set; }
public int yesterday_deaths { get; set; }
public int yesterday_open_cases { get; set; }
public int yesterday_recovered { get; set; }
public int yesterday_tests { get; set; }
public int yesterday_total_hospitalised_patients { get; set; }
}
public class Link1
{
public string href { get; set; }
public string rel { get; set; }
public string type { get; set; }
}
public class Sub_Regions
{
public string date { get; set; }
public string id { get; set; }
public string name { get; set; }
public string name_es { get; set; }
public string name_it { get; set; }
public string source { get; set; }
public int today_confirmed { get; set; }
public int today_deaths { get; set; }
public int today_new_confirmed { get; set; }
public int today_new_deaths { get; set; }
public int today_new_recovered { get; set; }
public int today_recovered { get; set; }
public float? today_vs_yesterday_confirmed { get; set; }
public float? today_vs_yesterday_deaths { get; set; }
public object today_vs_yesterday_recovered { get; set; }
public int yesterday_confirmed { get; set; }
public int yesterday_deaths { get; set; }
public int yesterday_recovered { get; set; }
}
public class Info
{
public string date { get; set; }
public string date_generation { get; set; }
public string yesterday { get; set; }
}
public class Metadata
{
public string by { get; set; }
public string[] url { get; set; }
}
public class Total
{
public string date { get; set; }
public string name { get; set; }
public string name_es { get; set; }
public string name_it { get; set; }
public string rid { get; set; }
public string source { get; set; }
public int today_confirmed { get; set; }
public int today_deaths { get; set; }
public int today_new_confirmed { get; set; }
public int today_new_deaths { get; set; }
public int today_new_open_cases { get; set; }
public int today_new_recovered { get; set; }
public int today_open_cases { get; set; }
public int today_recovered { get; set; }
public float today_vs_yesterday_confirmed { get; set; }
public float today_vs_yesterday_deaths { get; set; }
public float today_vs_yesterday_open_cases { get; set; }
public float today_vs_yesterday_recovered { get; set; }
public int yesterday_confirmed { get; set; }
public int yesterday_deaths { get; set; }
public int yesterday_open_cases { get; set; }
public int yesterday_recovered { get; set; }
}
you should correctly create classes that represent your response, for that, I would recommend this site that will help with that:
(https://json2csharp.com/)
you are not using correctly RestSharp, you can use use the generic version of Execute that accept the model to parse the sent json
var client = new RestClient("https://api.covid19tracking.narrativa.com/api/2020-03-22/country/" + "us");
client.Timeout = -1;
var request = new RestRequest(Method.GET);
var response = client.Execute<Rootobject>(request)?.Data;
to access your Dates object, you only need to do so,
var dates = response?.dates
Related
I know that this question is asked many times but still I'm struggling to understand this. I have below json to c# converted class.
// Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
public class Accessibility
{
public bool share { get; set; }
public bool comment { get; set; }
}
public class Avatar
{
public string #base { get; set; }
}
public class Beautifulnari
{
public List<Post> posts { get; set; }
public long totalViewsCount { get; set; }
}
public class CaptionSignals
{
public bool safe { get; set; }
public Unsafe #unsafe { get; set; }
}
public class Category
{
public string id { get; set; }
public string name { get; set; }
}
public class Count
{
public int likes { get; set; }
public int views { get; set; }
}
public class Datum
{
public Haythandi haythandi { get; set; }
public Beautifulnari beautifulnari { get; set; }
}
public class HashtagDatum
{
public string _id { get; set; }
public string hashTagId { get; set; }
public string hashtagName { get; set; }
}
public class Haythandi
{
public List<Post> posts { get; set; }
public int totalViewsCount { get; set; }
}
public class Loc
{
public string type { get; set; }
public List<double> coordinates { get; set; }
}
public class MediaLocation
{
public int isHLS { get; set; }
public bool isTranscoded { get; set; }
public double duration { get; set; }
public string #base { get; set; }
public string thumbNailPath { get; set; }
public string path { get; set; }
public int mediaType { get; set; }
public string f0 { get; set; }
public string thumbnail { get; set; }
public Transcoded transcoded { get; set; }
public string compressedThumbnailPath { get; set; }
public string oPath { get; set; }
public string resizedThumbnailPath { get; set; }
public Resolution resolution { get; set; }
public Thumbnails thumbnails { get; set; }
public string webPath { get; set; }
}
public class ModerationStatus
{
public int approval { get; set; }
public int payment { get; set; }
public bool isModerated { get; set; }
public string moderatedBy { get; set; }
public string approvedBy { get; set; }
public DateTime? approvalDate { get; set; }
public DateTime? moderationDate { get; set; }
public int isAccepted { get; set; }
public string acceptedBy { get; set; }
public DateTime acceptanceDate { get; set; }
public object hashtagRejectReason { get; set; }
public int isOriginalAudio { get; set; }
public object ogAudioAcceptedBy { get; set; }
public object ogAudioAcceptanceDate { get; set; }
public object ogAudioRejectReason { get; set; }
public string acceptedHashtagId { get; set; }
}
public class ModerationV2Array
{
public string moderatorId { get; set; }
public string moderatorName { get; set; }
public object moderationSignals { get; set; }
public string response { get; set; }
}
public class OwnerData
{
public Avatar avatar { get; set; }
public string _id { get; set; }
public string name { get; set; }
public string username { get; set; }
public string status { get; set; }
public string profilePic { get; set; }
public int isProfileVerified { get; set; }
public int isFollowed { get; set; }
public int tipEnabled { get; set; }
}
public class Post
{
public string _id { get; set; }
public MediaLocation mediaLocation { get; set; }
public TempMedia tempMedia { get; set; }
public Song song { get; set; }
public Count count { get; set; }
public Accessibility accessibility { get; set; }
public OwnerData ownerData { get; set; }
public ModerationStatus moderationStatus { get; set; }
public TaggedStatus taggedStatus { get; set; }
public List<string> etags { get; set; }
public bool isDuplicate { get; set; }
public bool isProcessed { get; set; }
public string caption { get; set; }
public List<string> hashtagIds { get; set; }
public string youtubeLink { get; set; }
public bool isPrivate { get; set; }
public int reportPostsCount { get; set; }
public string audioLang { get; set; }
public object cta_text { get; set; }
public string ip { get; set; }
public string country { get; set; }
public string city { get; set; }
public string versionCode { get; set; }
public string createdBy { get; set; }
public string postType { get; set; }
public string uploadSource { get; set; }
public bool isSpam { get; set; }
public bool isPremium { get; set; }
public int metaProcessed { get; set; }
public int isShoppable { get; set; }
public int isLiked { get; set; }
public bool onlyFollowers { get; set; }
public bool isPrivateByAdmin { get; set; }
public int isPinned { get; set; }
public int isPromoted { get; set; }
public int isMiningAllowed { get; set; }
public string s3RefId { get; set; }
public string userId { get; set; }
public object duplicateOfPostId { get; set; }
public List<HashtagDatum> hashtagData { get; set; }
public List<Category> categories { get; set; }
public string gender { get; set; }
public int shareCount { get; set; }
public int likeCount { get; set; }
public int commentCount { get; set; }
public int viewsCount { get; set; }
public string status { get; set; }
public string language { get; set; }
public string created_at { get; set; }
public List<object> spamReason { get; set; }
public List<object> taggedUsers { get; set; }
public int __v { get; set; }
public Loc loc { get; set; }
public string region { get; set; }
public bool? enableV2 { get; set; }
public List<ModerationV2Array> moderationV2Array { get; set; }
public bool? ignoreV2 { get; set; }
public bool? isPremiumV2 { get; set; }
public bool? isSpamV2 { get; set; }
public List<PremiumCCSignal> premiumCCSignals { get; set; }
}
public class PremiumCCSignal
{
public string moderatorId { get; set; }
public CaptionSignals captionSignals { get; set; }
}
public class Resolution
{
public int width { get; set; }
public int height { get; set; }
}
public class Root
{
public int code { get; set; }
public List<Datum> data { get; set; }
public string message { get; set; }
public bool hasmoreData { get; set; }
public object error { get; set; }
}
public class Song
{
public string _id { get; set; }
public string title { get; set; }
public string art { get; set; }
public string author { get; set; }
public string categoryName { get; set; }
public object albumName { get; set; }
public int startTime { get; set; }
public double endTime { get; set; }
public string acrId { get; set; }
}
public class TaggedStatus
{
public bool isTagged { get; set; }
public string taggedBy { get; set; }
public DateTime taggedDate { get; set; }
}
public class TempMedia
{
public int isHls { get; set; }
}
public class Thumbnails
{
public string w50 { get; set; }
public string w150 { get; set; }
public string w300 { get; set; }
public string w700 { get; set; }
}
public class Transcoded
{
public string p1024 { get; set; }
public string p480 { get; set; }
public string p720 { get; set; }
}
public class Unsafe
{
}
In this above JSON, classes mentioned below are dynamic keys into response JSON.
Haythandi
Beautifulnari
The problem is that values Haythandi and beautifulNari as class name (if convert to c#) which are actually ids of that particular record. How do I convert these id's into c# class?, I have tried multiple approaches like using Dictionaries, JObjects, dynamic and Expando classes but not result. Any help would be much appreciated.
I think you need change one of the 'character classes' to:
public class MyClassWithPosts // was Beautifulnari
{
public List<Post> posts { get; set; }
public long totalViewsCount { get; set; }
}
After that data can become a dictionary (update: a list of dictionaries):
public class Root
{
public int code { get; set; }
public List<Dictionary<string, MyClassWithPosts>> data { get; set; }
I'm trying to deserialize some json I got from here https://www.reddit.com/r/tf2/hot/.json?limit=10&rawjson=1 but all the examples with newtonsoft json.net are shown with simple json objects.
How would I go about deserializing this into a nice object?
You must create your own object and specify the object in the deserialization.
YourNewRootClass result =
JsonSerializer.Deserialize<YourNewRootClass>(jsonString);
You can use this site to create a dummy object with the json format that you require: https://json2csharp.com/
UPDATE
with your example:
Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
and then:
// Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
public class LinkFlairRichtext
{
public string e { get; set; }
public string t { get; set; }
}
public class MediaEmbed
{
}
public class RedditVideo
{
public int bitrate_kbps { get; set; }
public string fallback_url { get; set; }
public int height { get; set; }
public int width { get; set; }
public string scrubber_media_url { get; set; }
public string dash_url { get; set; }
public int duration { get; set; }
public string hls_url { get; set; }
public bool is_gif { get; set; }
public string transcoding_status { get; set; }
}
public class SecureMedia
{
public RedditVideo reddit_video { get; set; }
}
public class SecureMediaEmbed
{
}
public class AuthorFlairRichtext
{
public string e { get; set; }
public string t { get; set; }
public string a { get; set; }
public string u { get; set; }
}
public class Gildings
{
public int gid_1 { get; set; }
}
public class ResizedIcon
{
public string url { get; set; }
public int width { get; set; }
public int height { get; set; }
}
public class ResizedStaticIcon
{
public string url { get; set; }
public int width { get; set; }
public int height { get; set; }
}
public class AllAwarding
{
public int? giver_coin_reward { get; set; }
public string subreddit_id { get; set; }
public bool is_new { get; set; }
public int days_of_drip_extension { get; set; }
public int coin_price { get; set; }
public string id { get; set; }
public int? penny_donate { get; set; }
public string award_sub_type { get; set; }
public int coin_reward { get; set; }
public string icon_url { get; set; }
public int days_of_premium { get; set; }
public object tiers_by_required_awardings { get; set; }
public List<ResizedIcon> resized_icons { get; set; }
public int icon_width { get; set; }
public int static_icon_width { get; set; }
public object start_date { get; set; }
public bool is_enabled { get; set; }
public object awardings_required_to_grant_benefits { get; set; }
public string description { get; set; }
public object end_date { get; set; }
public int subreddit_coin_reward { get; set; }
public int count { get; set; }
public int static_icon_height { get; set; }
public string name { get; set; }
public List<ResizedStaticIcon> resized_static_icons { get; set; }
public string icon_format { get; set; }
public int icon_height { get; set; }
public int? penny_price { get; set; }
public string award_type { get; set; }
public string static_icon_url { get; set; }
}
public class Media
{
public RedditVideo reddit_video { get; set; }
}
public class Source
{
public string url { get; set; }
public int width { get; set; }
public int height { get; set; }
}
public class Resolution
{
public string url { get; set; }
public int width { get; set; }
public int height { get; set; }
}
public class Variants
{
}
public class Image
{
public Source source { get; set; }
public List<Resolution> resolutions { get; set; }
public Variants variants { get; set; }
public string id { get; set; }
}
public class Preview
{
public List<Image> images { get; set; }
public bool enabled { get; set; }
}
public class P
{
public int y { get; set; }
public int x { get; set; }
public string u { get; set; }
}
public class S
{
public int y { get; set; }
public int x { get; set; }
public string u { get; set; }
}
public class _34nbvtvyhht71
{
public string status { get; set; }
public string e { get; set; }
public string m { get; set; }
public List<P> p { get; set; }
public S s { get; set; }
public string id { get; set; }
}
public class Bec5guvyhht71
{
public string status { get; set; }
public string e { get; set; }
public string m { get; set; }
public List<P> p { get; set; }
public S s { get; set; }
public string id { get; set; }
}
public class _6bz9mhnlpet71
{
public string status { get; set; }
public string e { get; set; }
public string m { get; set; }
public List<P> p { get; set; }
public S s { get; set; }
public string id { get; set; }
}
public class Mgx8gqrlpet71
{
public string status { get; set; }
public string e { get; set; }
public string m { get; set; }
public List<P> p { get; set; }
public S s { get; set; }
public string id { get; set; }
}
public class _4eok02vlpet71
{
public string status { get; set; }
public string e { get; set; }
public string m { get; set; }
public List<P> p { get; set; }
public S s { get; set; }
public string id { get; set; }
}
public class _5oj0iz0jqet71
{
public string status { get; set; }
public string e { get; set; }
public string m { get; set; }
public List<P> p { get; set; }
public S s { get; set; }
public string id { get; set; }
}
public class _6dih3x0jqet71
{
public string status { get; set; }
public string e { get; set; }
public string m { get; set; }
public List<P> p { get; set; }
public S s { get; set; }
public string id { get; set; }
}
public class MediaMetadata
{
public _34nbvtvyhht71 _34nbvtvyhht71 { get; set; }
public Bec5guvyhht71 bec5guvyhht71 { get; set; }
public _6bz9mhnlpet71 _6bz9mhnlpet71 { get; set; }
public Mgx8gqrlpet71 mgx8gqrlpet71 { get; set; }
public _4eok02vlpet71 _4eok02vlpet71 { get; set; }
public _5oj0iz0jqet71 _5oj0iz0jqet71 { get; set; }
public _6dih3x0jqet71 _6dih3x0jqet71 { get; set; }
}
public class Item
{
public string caption { get; set; }
public string media_id { get; set; }
public int id { get; set; }
}
public class GalleryData
{
public List<Item> items { get; set; }
}
public class Data2
{
public object approved_at_utc { get; set; }
public string subreddit { get; set; }
public string selftext { get; set; }
public string author_fullname { get; set; }
public bool saved { get; set; }
public object mod_reason_title { get; set; }
public int gilded { get; set; }
public bool clicked { get; set; }
public string title { get; set; }
public List<LinkFlairRichtext> link_flair_richtext { get; set; }
public string subreddit_name_prefixed { get; set; }
public bool hidden { get; set; }
public int pwls { get; set; }
public string link_flair_css_class { get; set; }
public int downs { get; set; }
public int? thumbnail_height { get; set; }
public object top_awarded_type { get; set; }
public bool hide_score { get; set; }
public string name { get; set; }
public bool quarantine { get; set; }
public string link_flair_text_color { get; set; }
public double upvote_ratio { get; set; }
public string author_flair_background_color { get; set; }
public string subreddit_type { get; set; }
public int ups { get; set; }
public int total_awards_received { get; set; }
public MediaEmbed media_embed { get; set; }
public int? thumbnail_width { get; set; }
public string author_flair_template_id { get; set; }
public bool is_original_content { get; set; }
public List<object> user_reports { get; set; }
public SecureMedia secure_media { get; set; }
public bool is_reddit_media_domain { get; set; }
public bool is_meta { get; set; }
public object category { get; set; }
public SecureMediaEmbed secure_media_embed { get; set; }
public string link_flair_text { get; set; }
public bool can_mod_post { get; set; }
public int score { get; set; }
public object approved_by { get; set; }
public bool is_created_from_ads_ui { get; set; }
public bool author_premium { get; set; }
public string thumbnail { get; set; }
public object edited { get; set; }
public string author_flair_css_class { get; set; }
public List<AuthorFlairRichtext> author_flair_richtext { get; set; }
public Gildings gildings { get; set; }
public object content_categories { get; set; }
public bool is_self { get; set; }
public object mod_note { get; set; }
public double created { get; set; }
public string link_flair_type { get; set; }
public int wls { get; set; }
public object removed_by_category { get; set; }
public object banned_by { get; set; }
public string author_flair_type { get; set; }
public string domain { get; set; }
public bool allow_live_comments { get; set; }
public string selftext_html { get; set; }
public object likes { get; set; }
public object suggested_sort { get; set; }
public object banned_at_utc { get; set; }
public object view_count { get; set; }
public bool archived { get; set; }
public bool no_follow { get; set; }
public bool is_crosspostable { get; set; }
public bool pinned { get; set; }
public bool over_18 { get; set; }
public List<AllAwarding> all_awardings { get; set; }
public List<object> awarders { get; set; }
public bool media_only { get; set; }
public string link_flair_template_id { get; set; }
public bool can_gild { get; set; }
public bool spoiler { get; set; }
public bool locked { get; set; }
public string author_flair_text { get; set; }
public List<object> treatment_tags { get; set; }
public bool visited { get; set; }
public object removed_by { get; set; }
public object num_reports { get; set; }
public object distinguished { get; set; }
public string subreddit_id { get; set; }
public bool author_is_blocked { get; set; }
public object mod_reason_by { get; set; }
public object removal_reason { get; set; }
public string link_flair_background_color { get; set; }
public string id { get; set; }
public bool is_robot_indexable { get; set; }
public object report_reasons { get; set; }
public string author { get; set; }
public object discussion_type { get; set; }
public int num_comments { get; set; }
public bool send_replies { get; set; }
public string whitelist_status { get; set; }
public bool contest_mode { get; set; }
public List<object> mod_reports { get; set; }
public bool author_patreon_flair { get; set; }
public string author_flair_text_color { get; set; }
public string permalink { get; set; }
public string parent_whitelist_status { get; set; }
public bool stickied { get; set; }
public string url { get; set; }
public int subreddit_subscribers { get; set; }
public double created_utc { get; set; }
public int num_crossposts { get; set; }
public Media media { get; set; }
public bool is_video { get; set; }
public string post_hint { get; set; }
public Preview preview { get; set; }
public string url_overridden_by_dest { get; set; }
public bool? is_gallery { get; set; }
public MediaMetadata media_metadata { get; set; }
public GalleryData gallery_data { get; set; }
public string after { get; set; }
public int dist { get; set; }
public string modhash { get; set; }
public object geo_filter { get; set; }
public List<Child> children { get; set; }
public object before { get; set; }
}
public class Child
{
public string kind { get; set; }
public Data data { get; set; }
}
public class Root
{
public string kind { get; set; }
public Data data { get; set; }
}
After a quick look at available information online. Yikes, that format is annoying.
I would suggest you start by defining a base type, a subclass for each "kind" and a custom converter to deserialise them. Which might look something like this;
public abstract class RedditBase {
}
public class RedditListing : RedditBase {
public string Before { get; set; }
public string After { get; set; }
public List<RedditBase> Children { get; set; }
}
public class RedditConverter : JsonConverter<RedditBase>
{
public override void WriteJson(JsonWriter writer, RedditBase value, JsonSerializer serializer)
=> throw new NotImplementedException();
public override RedditBase ReadJson(JsonReader reader, Type objectType, RedditBase existingValue, bool hasExistingValue, JsonSerializer serializer)
{
var obj = JObject.Load(reader);
var data = (JObject)obj["data"];
switch ((string)obj["kind"])
{
case "Listing":
{
var list = new RedditListing();
serializer.Populate(data.CreateReader(), list);
return list;
}
default:
throw new NotImplementedException();
}
}
}
I am use api use variable date whene date change the object name change like this if i have to get data of this day i use this :https://api.covid19tracking.narrativa.com/api/2020-11-05/country/us
and the result of json object is like this :
and if i have to choose other date i change the date and the variable of date object is change like this if i have to get data of 2020-10-11 ,i calll this:
https://api.covid19tracking.narrativa.com/api/2020-11-05/country/us , and this is image show the result and the change of object date
the problem is if i deserialize the api i get result from , metadata object ,total object , updated_at , and dates object and the other object date and countries give me this error
:NullReferenceException: Object reference not set to an instance of an object
I use https://json2csharp.com/ to get class from json and this is my code :
var client = new RestClient("https://api.covid19tracking.narrativa.com/api/2020-11-05/country/us");
client.Timeout = -1;
var request = new RestRequest(Method.GET);
// request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
Root response = client.Execute<Root>(request)?.Data;
var paystoday_confirmed = response?.dates.date.countries.US.today_confirmed;
if (paystoday_confirmed != null)
{
Debug.Log("Confirmed :" + paystoday_confirmed);
}
and this is my object's
public class Link
{
public string href { get; set; }
public string rel { get; set; }
public string type { get; set; }
}
public class Link2
{
public string href { get; set; }
public string rel { get; set; }
public string type { get; set; }
}
public class SubRegion
{
public string date { get; set; }
public string id { get; set; }
public string name { get; set; }
public string name_es { get; set; }
public string name_it { get; set; }
public string source { get; set; }
public int today_confirmed { get; set; }
public int today_deaths { get; set; }
public int today_new_confirmed { get; set; }
public int today_new_deaths { get; set; }
public int today_new_recovered { get; set; }
public int today_recovered { get; set; }
public double? today_vs_yesterday_confirmed { get; set; }
public double? today_vs_yesterday_deaths { get; set; }
public object today_vs_yesterday_recovered { get; set; }
public int yesterday_confirmed { get; set; }
public int yesterday_deaths { get; set; }
public int yesterday_recovered { get; set; }
}
public class Region
{
public string date { get; set; }
public string id { get; set; }
public List<Link2> links { get; set; }
public string name { get; set; }
public string name_es { get; set; }
public string name_it { get; set; }
public string source { get; set; }
public List<SubRegion> sub_regions { get; set; }
public int today_confirmed { get; set; }
public int today_deaths { get; set; }
public int today_new_confirmed { get; set; }
public int today_new_deaths { get; set; }
public int today_new_open_cases { get; set; }
public int today_new_recovered { get; set; }
public int today_new_tests { get; set; }
public int today_new_total_hospitalised_patients { get; set; }
public int today_open_cases { get; set; }
public int today_recovered { get; set; }
public int today_tests { get; set; }
public int today_total_hospitalised_patients { get; set; }
public double? today_vs_yesterday_confirmed { get; set; }
public double? today_vs_yesterday_deaths { get; set; }
public double today_vs_yesterday_open_cases { get; set; }
public double? today_vs_yesterday_recovered { get; set; }
public double today_vs_yesterday_tests { get; set; }
public double? today_vs_yesterday_total_hospitalised_patients { get; set; }
public int yesterday_confirmed { get; set; }
public int yesterday_deaths { get; set; }
public int yesterday_open_cases { get; set; }
public int yesterday_recovered { get; set; }
public int yesterday_tests { get; set; }
public int yesterday_total_hospitalised_patients { get; set; }
}
public class US
{
public string date { get; set; }
public string id { get; set; }
public List<Link> links { get; set; }
public string name { get; set; }
public string name_es { get; set; }
public string name_it { get; set; }
public List<Region> regions { get; set; }
public string source { get; set; }
public int today_confirmed { get; set; }
public int today_deaths { get; set; }
public int today_new_confirmed { get; set; }
public int today_new_deaths { get; set; }
public int today_new_open_cases { get; set; }
public int today_new_recovered { get; set; }
public int today_open_cases { get; set; }
public int today_recovered { get; set; }
public double today_vs_yesterday_confirmed { get; set; }
public double today_vs_yesterday_deaths { get; set; }
public double today_vs_yesterday_open_cases { get; set; }
public double today_vs_yesterday_recovered { get; set; }
public int yesterday_confirmed { get; set; }
public int yesterday_deaths { get; set; }
public int yesterday_open_cases { get; set; }
public int yesterday_recovered { get; set; }
}
public class Countries
{
public US US { get; set; }
}
public class Info
{
public string date { get; set; }
public string date_generation { get; set; }
public string yesterday { get; set; }
}
public class _20201102
{
public Countries countries { get; set; }
public Info info { get; set; }
}
public class Dates
{
[JsonProperty("2020-11-02")]
public _20201102 date { get; set; }
}
public class Metadata
{
public string by { get; set; }
public List<string> url { get; set; }
}
public class Total
{
public string date { get; set; }
public string name { get; set; }
public string name_es { get; set; }
public string name_it { get; set; }
public string rid { get; set; }
public string source { get; set; }
public int today_confirmed { get; set; }
public int today_deaths { get; set; }
public int today_new_confirmed { get; set; }
public int today_new_deaths { get; set; }
public int today_new_open_cases { get; set; }
public int today_new_recovered { get; set; }
public int today_open_cases { get; set; }
public int today_recovered { get; set; }
public double today_vs_yesterday_confirmed { get; set; }
public double today_vs_yesterday_deaths { get; set; }
public double today_vs_yesterday_open_cases { get; set; }
public double today_vs_yesterday_recovered { get; set; }
public int yesterday_confirmed { get; set; }
public int yesterday_deaths { get; set; }
public int yesterday_open_cases { get; set; }
public int yesterday_recovered { get; set; }
}
public class Root
{
public Dates dates { get; set; }
public Metadata metadata { get; set; }
public Total total { get; set; }
public string updated_at { get; set; }
}
And this is the error on unity
It will work best if you use dictionaries.
You can make your dates and countries property a dictionary.
dates - Dates needs to be a dictionary because you can get data for different dates so the date will change
countries - The service u are using support other countries. If you change the countries to a dictionary, then the structure below should work for any country, not just for US.
Your code structure will then look something like this:
public class Root
{
public Dictionary<string, Date> dates {get;set;}
public Metadata metadata { get; set; }
public Total total { get; set; }
public string updated_at { get; set; }
}
public class Date
{
public Dictionary<string, Country> countries {get;set;}
public Info info {get;set;}
}
public class Country
{
....
//Country properties here
}
public class Info
{
....
//Info properties here
}
public class Metadata
{
....
//Metadata properties here
}
public class Total
{
....
//Total properties here
}
you should then be able to process the data as follow
foreach(var kvp in root.dates)
{
// the key will be the date eg. '2020-11-05'.
// This you can convert to a date using DateTime.Parse() if you need too.
Console.WriteLine(kvp.Key);
// The value will be the Date object
var dateObj = kvp.Value;
var info = dateObj.info;
foreach(var kvp2 in dateObj.countries)
{
Console.WriteLine(kvp2.Key); // this will be the country eg. 'US'
var countryDetails = kvp2.Value // this will be the Country object
}
}
Or just change your code too:
(note: you will need to know exactly what date was returned)
var paystoday_confirmed = response?.dates["2020-11-05"].countries["US"].today_confirmed;
if (paystoday_confirmed != null)
{
Debug.Log("Confirmed :" + paystoday_confirmed);
}
As already stated in the Comments your main issue here is that you hardcoded
public class Dates
{
[JsonProperty("2020-11-02")]
public _20201102 date { get; set; }
}
But as you can see in your second result the date simply is not 2020-11-02 but rather 2020-10-11!
Therefore in this case there is no object in the json representing the data object => It will be the default reference value null.
So how to solve this?
You could instead use a Dictionary .. however it depends a lot on how your JSON library works. I know that at least with JSON .Net the following should work
public class Root
{
public Dictionary<string, Date> dates { get; set; }
public Metadata metadata { get; set; }
public Total total { get; set; }
public string updated_at { get; set; }
}
public class Date
{
public Dictionary<string, Country> countries { get; set; }
public Info info { get; set; }
}
public class Country
{
public string date { get; set; }
public string id { get; set; }
public List<Link> links { get; set; }
public string name { get; set; }
public string name_es { get; set; }
public string name_it { get; set; }
public List<Region> regions { get; set; }
public string source { get; set; }
public int today_confirmed { get; set; }
public int today_deaths { get; set; }
public int today_new_confirmed { get; set; }
public int today_new_deaths { get; set; }
public int today_new_open_cases { get; set; }
public int today_new_recovered { get; set; }
public int today_open_cases { get; set; }
public int today_recovered { get; set; }
public double today_vs_yesterday_confirmed { get; set; }
public double today_vs_yesterday_deaths { get; set; }
public double today_vs_yesterday_open_cases { get; set; }
public double today_vs_yesterday_recovered { get; set; }
public int yesterday_confirmed { get; set; }
public int yesterday_deaths { get; set; }
public int yesterday_open_cases { get; set; }
public int yesterday_recovered { get; set; }
}
This also sounds more logic since dates indicates that there might be more then one item. And also countries sounds like there might not only be US but also other countries, maybe even multiple entries.
You would then access that e.g. like
foreach(var date in response.dates)
{
foreach(var country in date.value)
{
var paystoday_confirmed = country.value.today_confirmed;
Debug.Log($"Confirmed {paystoday_confirmed} cases for the {date.key} in {country.key}");
}
}
As complete alternative in the case you only need one certain field of your request anyway you could also use SimpleJson (simply copy the provided scripts somewhere into your project) and access them like
var root = JSON.Parse(theJsonString);
var paystoday_confirmed = root["Dates"]["2020-11-05"]["countries"]["US"]["today_confirmed"].AsInt();
For both solutions you will have to get rid of that RestClient package and rather do the UnityWebRequest.Get yourself and use the returned string instead.
I am developing online aircraft sales system.
But I have a problem..
A URL address have:
string urlFlightSearch = "https://api.iati.com/rest/flightSearch/" + ado.iatiKod + "";
A have class "iati.cs" in codes
public class iati
{
public class flightSearch
{
public string fromAirport { get; set; }
public bool allinFromCity { get; set; }
public string toAirport { get; set; }
public string fromDate { get; set; }
public string returnDate { get; set; }
public string adult { get; set; }
public string currency { get; set; }
}
public class Leg
{
public string flightNo { get; set; }
public string aircraft { get; set; }
public string operatorCode { get; set; }
public string operatorName { get; set; }
public string departureAirport { get; set; }
public string departureTime { get; set; }
public string departureAirportName { get; set; }
public string departureCityName { get; set; }
public string arrivalAirport { get; set; }
public string arrivalTime { get; set; }
public string arrivalAirportName { get; set; }
public string arrivalCityName { get; set; }
}
public class Detail
{
public double price { get; set; }
public double serviceFee { get; set; }
public double tax { get; set; }
public int suplement { get; set; }
}
public class Fare
{
public double totalSingleAdultFare { get; set; }
public string currency { get; set; }
public string type { get; set; }
public List<string> segmentNames { get; set; }
public int freeSeatCount { get; set; }
public Detail detail { get; set; }
}
public class Flight
{
public string id { get; set; }
public string providerKey { get; set; }
public string pricingType { get; set; }
public int packageId { get; set; }
public List<Leg> legs { get; set; }
public List<Fare> fares { get; set; }
public int segmentCount { get; set; }
public int baggage { get; set; }
public int flightTimeHour { get; set; }
public int flightTimeMinute { get; set; }
public int layoverTime { get; set; }
public bool hasCip { get; set; }
public bool canBook { get; set; }
public bool canRezerve { get; set; }
public bool dayCross { get; set; }
public bool returnFlight { get; set; }
}
public class Result
{
public string searchId { get; set; }
public List<Flight> flights { get; set; }
}
public class RootObject
{
public Result result { get; set; }
}
}
And posting...
WebClient wc = new WebClient();
var serializer = new JavaScriptSerializer();
iati.flightSearch search = new iati.flightSearch()
{
fromAirport = "IST",
allinFromCity = true,
toAirport = "AYT",
fromDate = "2013-12-23",
returnDate = "2013-12-30",
adult = "1",
currency = "EUR"
};
var serializedResult = serializer.Serialize(search);
wc.Headers[HttpRequestHeader.ContentType] = "application/json";
string result = wc.UploadString(urlFlightSearch, serializedResult);
iati.Flight flight = serializer.Deserialize<iati.Flight>(result);
But the result returned is always coming up empty.
Regards.
use Newtonsoft
JsonConvert.DeserializeObject(result);
I am using the following tutorial to parse a JSON document.
http://www.drowningintechnicaldebt.com/ShawnWeisfeld/archive/2010/08/22/using-c-4.0-and-dynamic-to-parse-json.aspx
The JSON document that I am trying to parse can be accessed here:
http://www.visitproject.co.uk/Tweets/Ireland.txt
JavaScriptSerializer jss = new JavaScriptSerializer();
jss.RegisterConverters(new JavaScriptConverter[] { new DynamicJsonConverter() });
dynamic tweets = jss.Deserialize(json, typeof(object)) as dynamic;
foreach (var tweettext in tweets.statuses.text)
{
Console.WriteLine("Tweet: " + tweettext);
}
I am able to perform a watch on tweets.statuses and it does contain a collection of tweets. I would like to get the text value from each tweet. The only thing I can see that is different for the tutorial is that it is an array in JSON and I expect that this is why it is not working. Does anyone have any ideas? Thank you for your help!
You could use LINQ to JSON, like this:
// Parse JSON
JObject o = JObject.Parse(json);
Read LINQ to JSON documentation for details on how to query for the pieces of JSON you want.
You can simply copy paste the code below and get your answer.
This is how i parsed your json data.
I created classes based on your json
public class Metadata
{
public string result_type { get; set; }
public string iso_language_code { get; set; }
}
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 bool following { get; set; }
public bool follow_request_sent { get; set; }
public bool notifications { get; set; }
public string profile_banner_url { get; set; }
}
public class Large
{
public int w { get; set; }
public int h { get; set; }
public string resize { get; set; }
}
public class Medium2
{
public int w { get; set; }
public int h { get; set; }
public string resize { get; set; }
}
public class Thumb
{
public int w { get; set; }
public int h { get; set; }
public string resize { get; set; }
}
public class Small
{
public int w { get; set; }
public int h { get; set; }
public string resize { get; set; }
}
public class Sizes
{
public Large large { get; set; }
public Medium2 medium { get; set; }
public Thumb thumb { get; set; }
public Small small { get; set; }
}
public class Medium
{
public object id { get; set; }
public string id_str { get; set; }
public List<int> indices { get; set; }
public string media_url { get; set; }
public string media_url_https { get; set; }
public string url { get; set; }
public string display_url { get; set; }
public string expanded_url { get; set; }
public string type { get; set; }
public Sizes sizes { get; set; }
public long source_status_id { get; set; }
public string source_status_id_str { 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 List<Medium> media { get; set; }
}
public class Metadata2
{
public string result_type { get; set; }
public string iso_language_code { get; set; }
}
public class Description2
{
public List<object> urls { get; set; }
}
public class Url4
{
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 Url3
{
public List<Url4> urls { get; set; }
}
public class Entities3
{
public Description2 description { get; set; }
public Url3 url { get; set; }
}
public class User2
{
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 Entities3 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_banner_url { 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 bool following { get; set; }
public bool follow_request_sent { get; set; }
public bool notifications { get; set; }
}
public class Medium4
{
public int w { get; set; }
public int h { get; set; }
public string resize { get; set; }
}
public class Large2
{
public int w { get; set; }
public int h { get; set; }
public string resize { get; set; }
}
public class Thumb2
{
public int w { get; set; }
public int h { get; set; }
public string resize { get; set; }
}
public class Small2
{
public int w { get; set; }
public int h { get; set; }
public string resize { get; set; }
}
public class Sizes2
{
public Medium4 medium { get; set; }
public Large2 large { get; set; }
public Thumb2 thumb { get; set; }
public Small2 small { get; set; }
}
public class Medium3
{
public long id { get; set; }
public string id_str { get; set; }
public List<int> indices { get; set; }
public string media_url { get; set; }
public string media_url_https { get; set; }
public string url { get; set; }
public string display_url { get; set; }
public string expanded_url { get; set; }
public string type { get; set; }
public Sizes2 sizes { get; set; }
}
public class Entities4
{
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 List<Medium3> media { get; set; }
}
public class RetweetedStatus
{
public Metadata2 metadata { get; set; }
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 long? in_reply_to_status_id { get; set; }
public string in_reply_to_status_id_str { get; set; }
public int? in_reply_to_user_id { get; set; }
public string in_reply_to_user_id_str { get; set; }
public string in_reply_to_screen_name { get; set; }
public User2 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 Entities4 entities { get; set; }
public bool favorited { get; set; }
public bool retweeted { get; set; }
public bool possibly_sensitive { get; set; }
public string lang { get; set; }
}
public class Status
{
public Metadata metadata { get; set; }
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 long? in_reply_to_status_id { get; set; }
public string in_reply_to_status_id_str { get; set; }
public int? in_reply_to_user_id { get; set; }
public string in_reply_to_user_id_str { get; set; }
public string 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 bool possibly_sensitive { get; set; }
public string lang { get; set; }
public RetweetedStatus retweeted_status { get; set; }
}
public class SearchMetadata
{
public double completed_in { get; set; }
public long max_id { get; set; }
public string max_id_str { get; set; }
public string next_results { get; set; }
public string query { get; set; }
public string refresh_url { get; set; }
public int count { get; set; }
public int since_id { get; set; }
public string since_id_str { get; set; }
}
public class RootObject
{
public List<Status> statuses { get; set; }
public SearchMetadata search_metadata { get; set; }
}
And i parsed your data by using the following method
public void PARSEVALUES(string jsonValue)//jsonValue contains your json
{
JavaScriptSerializer jss = new JavaScriptSerializer();
RootObject r = jss.Deserialize<RootObject>(jsonValue);
foreach (var tweetText in r.statuses)
{
string val = tweetText.text;
}
}