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();
}
}
}
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 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 made a code for deserialize this JSON
First of all, I've created a class:
public class Self
{
public string href { get; set; }
}
public class Soccerseason
{
public string href { get; set; }
}
public class HomeTeam
{
public string href { get; set; }
}
public class AwayTeam
{
public string href { get; set; }
}
public class Links
{
public Self self { get; set; }
public Soccerseason soccerseason { get; set; }
public HomeTeam homeTeam { get; set; }
public AwayTeam awayTeam { get; set; }
}
public class Result
{
public int goalsHomeTeam { get; set; }
public int goalsAwayTeam { get; set; }
}
public class LastHomeWinHomeTeam
{
public Links _links { get; set; }
public string date { get; set; }
public object status { get; set; }
public int matchday { get; set; }
public string homeTeamName { get; set; }
public string awayTeamName { get; set; }
public Result result { get; set; }
}
public class LastWinHomeTeam
{
public Links _links { get; set; }
public string date { get; set; }
public object status { get; set; }
public int matchday { get; set; }
public string homeTeamName { get; set; }
public string awayTeamName { get; set; }
public Result result { get; set; }
}
public class LastAwayWinAwayTeam
{
public Links _links { get; set; }
public string date { get; set; }
public object status { get; set; }
public int matchday { get; set; }
public string homeTeamName { get; set; }
public string awayTeamName { get; set; }
public Result result { get; set; }
}
public class LastWinAwayTeam
{
public Links _links { get; set; }
public string date { get; set; }
public object status { get; set; }
public int matchday { get; set; }
public string homeTeamName { get; set; }
public string awayTeamName { get; set; }
public Result result { get; set; }
}
public class Head2head
{
public int count { get; set; }
public string timeFrameStart { get; set; }
public string timeFrameEnd { get; set; }
public int homeTeamWins { get; set; }
public int awayTeamWins { get; set; }
public int draws { get; set; }
public LastHomeWinHomeTeam lastHomeWinHomeTeam { get; set; }
public LastWinHomeTeam lastWinHomeTeam { get; set; }
public LastAwayWinAwayTeam lastAwayWinAwayTeam { get; set; }
public LastWinAwayTeam lastWinAwayTeam { get; set; }
public List<Fixture> fixtures { get; set; }
}
public class Fixture
{
public Links _links { get; set; }
public string date { get; set; }
public object status { get; set; }
public int matchday { get; set; }
public string homeTeamName { get; set; }
public string awayTeamName { get; set; }
public Result result { get; set; }
}
public class RootObject
{
public List<Fixture> fixture { get; set; }
public Head2head head2head { get; set; }
}
So I made a code for parsing a request, and return a responseText:
string responseText = Parser.Request(link); //Parser is the class that perform HttpRequest
so far no problem.
I've declarated the object for deserialize the responseText returned:
var obj = JsonConvert.DeserializeObject<Fixtures.RootObject>(responseText);
and next I do the foreach:
foreach (var fixture in obj.fixture)
{do stuff..}
but in obj.fixture I get null and I don't know why. Because all JSON is deserialized correcly. What am I doing wrong?
The key in the JSON is "fixtures" - it needs to match the property name of your class exactly. Change
public List<Fixture> fixture { get; set; }
to
public List<Fixture> fixtures { get; set; }
Alternatively, you can use the JsonProperty attribute:
[JsonProperty("fixtures")]
public List<Fixture> fixture { get; set; }
I have the following class object structure:
public class StatusObj3
{
public int status { get; set; }
public DataObj3 data { get; set; }
}
public class DataObj3
{
public string survey_id { get; set; }
public string date_created { get; set; }
public string date_modified { get; set; }
public int custom_variable_count { get; set; }
public List<Custom_VariablesObj> custom_variables { get; set; }
public int language_id { get; set; }
public int num_responses { get; set; }
public int question_count { get; set; }
public string nickname { get; set; }
public TitleObj title { get; set; }
public List<PagesObj> pages { get; set; }
}
public class Custom_VariablesObj
{
public string variable_label { get; set; }
public string question_id { get; set; }
}
public class TitleObj
{
public bool enabled { get; set; }
public string text { get; set; }
}
public class PagesObj
{
string page_id { get; set; }
string heading { get; set; }
string sub_heading { get; set; }
public List<QuestionObj> questions { get; set; }
}
public class QuestionObj
{
public string question_id { get; set; }
public string heading { get; set; }
public string position { get; set; }
public QuestionTypeObj type { get; set; }
public List<AnswerObj> answers { get; set; }
}
public class QuestionTypeObj
{
public string family { get; set; }
public string subtype { get; set; }
}
public class AnswerObj
{
public string answer_id { get; set; }
public int position { get; set; }
public string text { get; set; }
public string type { get; set; }
public bool visible { get; set; }
public int weight { get; set; }
public bool apply_all_rows { get; set; }
public bool is_answer { get; set; }
public List<ItemsObj> items { get; set; }
}
public class ItemsObj
{
public string answer_id { get; set; }
public int position { get; set; }
public string type { get; set; }
public string text { get; set; }
}
I 've deserialized json into this object via:
var results_SurveyDetails = deserializer.Deserialize<StatusObj3>(json_returned);
I'm trying to loop thru the pages by:
foreach (var page in results_SurveyDetails.data.pages)
However, not all members of page are available to use.
Only the page.questions is there and not page_id, heading and subheading.
What am I doing wrong?
You are missing public on your other properties in class PagesObj.
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;
}
}