I am working a Xamarin.Forms App that uses the Azure Face API. With this API you retrieve a JSON response (See Below).
I want to extract the gender of the person in the image but am having trouble with it as I am very new to this.
I extract the full JSON response into a string but I would like to be able to extract data such as the 'Gender' or the 'Age' of the person in the image.
[{"faceId":"9448dfe4-afb6-4557-94fe-010fc439ff36","faceRectangle":{"top":635,"left":639,"width":789,"height":789},"faceAttributes":{"smile":0.187,"headPose":{"pitch":0.0,"roll":-1.6,"yaw":-7.9},"gender":"male","age":34.6,"facialHair":{"moustache":0.5,"beard":0.6,"sideburns":0.6},"glasses":"NoGlasses","emotion":{"anger":0.0,"contempt":0.69,"disgust":0.0,"fear":0.0,"happiness":0.187,"neutral":0.12,"sadness":0.002,"surprise":0.0},"blur":{"blurLevel":"low","value":0.15},"exposure":{"exposureLevel":"overExposure","value":0.85},"noise":{"noiseLevel":"medium","value":0.42},"makeup":{"eyeMakeup":false,"lipMakeup":false},"accessories":[],"occlusion":{"foreheadOccluded":false,"eyeOccluded":false,"mouthOccluded":false},"hair":{"bald":0.02,"invisible":false,"hairColor":[{"color":"brown","confidence":1.0},{"color":"black","confidence":0.95},{"color":"other","confidence":0.22},{"color":"blond","confidence":0.11},{"color":"gray","confidence":0.05},{"color":"red","confidence":0.04}]}}}]
This is how I set the JSON data to a string.
string contentString = await response.Content.ReadAsStringAsync();
You usually want to create a class that represents your response e. g. Person. Then you could use the Newtonsoft.Json nuget package to deserialize the object.:
var person = JsonConvert.DeserializeObject<Person>(contentString);
Now you can access the values like:
person.Gender
Using Newtonsoft.Json:
var results = JsonConvert.DeserializeObject<AzureFace>(contentString);
Debug.WriteLine(results.faceAttributes.age);
C# Model Used (via http://jsonutils.com)
public class FaceRectangle
{
public int top { get; set; }
public int left { get; set; }
public int width { get; set; }
public int height { get; set; }
}
public class HeadPose
{
public double pitch { get; set; }
public double roll { get; set; }
public double yaw { get; set; }
}
public class FacialHair
{
public double moustache { get; set; }
public double beard { get; set; }
public double sideburns { get; set; }
}
public class Emotion
{
public double anger { get; set; }
public double contempt { get; set; }
public double disgust { get; set; }
public double fear { get; set; }
public double happiness { get; set; }
public double neutral { get; set; }
public double sadness { get; set; }
public double surprise { get; set; }
}
public class Blur
{
public string blurLevel { get; set; }
public double value { get; set; }
}
public class Exposure
{
public string exposureLevel { get; set; }
public double value { get; set; }
}
public class Noise
{
public string noiseLevel { get; set; }
public double value { get; set; }
}
public class Makeup
{
public bool eyeMakeup { get; set; }
public bool lipMakeup { get; set; }
}
public class Occlusion
{
public bool foreheadOccluded { get; set; }
public bool eyeOccluded { get; set; }
public bool mouthOccluded { get; set; }
}
public class HairColor
{
public string color { get; set; }
public double confidence { get; set; }
}
public class Hair
{
public double bald { get; set; }
public bool invisible { get; set; }
public IList<HairColor> hairColor { get; set; }
}
public class FaceAttributes
{
public double smile { get; set; }
public HeadPose headPose { get; set; }
public string gender { get; set; }
public double age { get; set; }
public FacialHair facialHair { get; set; }
public string glasses { get; set; }
public Emotion emotion { get; set; }
public Blur blur { get; set; }
public Exposure exposure { get; set; }
public Noise noise { get; set; }
public Makeup makeup { get; set; }
public IList<object> accessories { get; set; }
public Occlusion occlusion { get; set; }
public Hair hair { get; set; }
}
public class AzureFace
{
public string faceId { get; set; }
public FaceRectangle faceRectangle { get; set; }
public FaceAttributes faceAttributes { get; set; }
}
Related
i'm trying to run through some JSON seralisation into some objects. pretty straight forward stuff.
for some reason i have the first part working as expected, it seralises perfectly.
the moment i wrap this JSON in an additional element the Deseralize Object passes, but the object is empty... i cannot spot the issue and i cannot seem to debug what's going on here.
string UIElement = "{\"Name\":\"X1144\",\"Order\":1,\"Tvalue\":\"int\",\"BindValue\":null,\"Default\":null,\"Disabled\":false,\"Mandatory\":true,\"MandatoryMessage\":\"this is a mandatory field\",\"Label\":\"<B> THIS is a HTML</b> label\",\"ToolTip\":\"just a tooltip\",\"PolicyProcess\":[{\"URL\":\"https://google.com\"}],\"Type\":\"RadzenColorPicker\",\"TypeOptions\":[{\"Name\":\"showHSV\",\"Value\":\"True\"},{\"Name\":\"showRGBA\",\"Value\":\"True\"},{\"Name\":\"ShowColors\",\"Value\":\"True\"},{\"Name\":\"showButton\",\"Value\":\"True\"}],\"ItemsType\":null,\"Items\":[],\"Scorable\":false,\"Score\":0,\"Visibility\":true,\"VisibilitySettings\":{\"Condition\":\"OR\",\"Rules\":[{\"Id\":\"X1234\",\"Value\":\"Yes\"},{\"Id\":\"X1222\",\"Value\":\"Yes\"}]},\"KMRs\":false,\"KMRsSettings\":[],\"Docs\":false,\"DocsSettings\":[],\"AutoFill\":true,\"AutoFillSettings\":{\"Value\":\"#999999\",\"Condition\":\"AND\",\"Rules\":[{\"Id\":\"X1234\",\"Value\":\"No\"},{\"Id\":\"X1234\",\"Value\":\"No\"}]}}";
RadzenUIElement element = JsonConvert.DeserializeObject<RadzenUIElement>(UIElement);
Console.WriteLine("UIElement " + element.Name);
foreach (var item in element.VisibilitySettings.Rules)
{
Console.WriteLine( item.Value.ToString());
}
string RadzenPanel = "{\"RadzenPanel\":{\"Id\":\"asfdgsertw34t43t34\",\"RadzenUiElement\":{\"Name\":\"X1144\",\"Order\":1,\"Tvalue\":\"int\",\"BindValue\":null,\"Default\":null,\"Disabled\":false,\"Mandatory\":true,\"MandatoryMessage\":\"this is a mandatory field\",\"Label\":\"<B> THIS is a HTML</b> label\",\"ToolTip\":\"just a tooltip\",\"PolicyProcess\":[{\"URL\":\"https://google.com\"}],\"Type\":\"RadzenColorPicker\",\"TypeOptions\":[{\"Name\":\"showHSV\",\"Value\":\"True\"},{\"Name\":\"showRGBA\",\"Value\":\"True\"},{\"Name\":\"ShowColors\",\"Value\":\"True\"},{\"Name\":\"showButton\",\"Value\":\"True\"}],\"ItemsType\":null,\"Items\":[],\"Scorable\":false,\"Score\":0,\"Visibility\":true,\"VisibilitySettings\":{\"Condition\":\"OR\",\"Rules\":[{\"Id\":\"X1234\",\"Value\":\"Yes\"},{\"Id\":\"X1222\",\"Value\":\"Yes\"}]},\"KMRs\":false,\"KMRsSettings\":[],\"Docs\":false,\"DocsSettings\":[],\"AutoFill\":true,\"AutoFillSettings\":{\"Value\":\"#999999\",\"Condition\":\"AND\",\"Rules\":[{\"Id\":\"X1234\",\"Value\":\"No\"},{\"Id\":\"X1234\",\"Value\":\"No\"}]}}}}";
RadzenPanel panels = JsonConvert.DeserializeObject<RadzenPanel>(RadzenPanel);
Console.WriteLine("elements in panels " + panels.Id);
the output from this code is below;
UIElement X1144
Yes
Yes
elements in panels
as i progress i'm looking to enhance the RadzenPanel to hold an array of the UIElements, but right now i cannot get it to parse a single item..
the object structure looks like this;
public class RadzenPanel
{
public string Id { get; set; }
public RadzenUIElement RadzenUiElement { get; set; }
}
public class RadzenUIElement
{
public string Name { get; set; }
public int Order { get; set; }
public string Tvalue { get; set; }
public string BindValue { get; set; }
public string Default { get; set; }
public bool Disabled { get; set; }
public bool Mandatory { get; set; }
public string MandatoryMessage { get; set; }
public string Label { get; set; }
public string ToolTip { get; set; }
public PolicyProcessLink[] PolicyProcess{ get; set; }
public string Type { get; set; }
public TypeOptions[] TypeOptions { get; set; }
public string ItemsType { get; set; }
public Items[] Items { get; set; }
public bool Scorable { get; set; }
public double ContributionScore { get; set; }
public bool Visibility { get; set; }
public VisibilitySettings VisibilitySettings { get; set; }
public bool KMRs { get; set; }
public KMRsSettings[] KMRsSettings { get; set; }
public bool Docs { get; set; }
public DocsSettings[] DocsSettings{ get; set; }
public bool AutoFill { get; set; }
public AutoFillSettings AutoFillSettings { get; set; }
}
public class PolicyProcessLink
{
public string URL { get; set; }
}
public class TypeConstants
{
public const string RadzenCheckbox = "RadzenCheckbox";
public const string RadzenCheckboxList = "RadzenCheckboxList";
public const string RadzenColorPicker = "RadzenColorPicker";
public const string RadzenDatePicker = "RadzenDatePicker";
public const string RadzenDropDown = "RadzenDropDown";
}
public class TypeOptions
{
public string Name { get; set; }
public string Value { get; set; }
}
public class Items
{
public string Name { get; set; }
public string Value { get; set; }
public string BGColor { get; set; }
public string TColor { get; set; }
public bool IsScore { get; set; }
public double Score { get; set; }
public bool IsNa { get; set; }
public string KMRIndicator{ get; set; }
public string DocsIncicator { get; set; }
}
public class VisibilitySettings
{
public bool Value { get; set; }
public string Condition { get; set; }
public Rules[] Rules { get; set; }
}
public class Rules
{
public string Id { get; set; }
public string Value { get; set; }
}
public class KMRsSettings
{
public Guid Id { get; set; }
public double Weighting { get; set; }
}
public class DocsSettings
{
public Guid Id { get; set; }
public double Weighting { get; set; }
}
public class AutoFillSettings
{
public string Value { get; set; }
public string Condition { get; set; }
public Rules[] Rules { get; set; }
}
not sure what the exact problem was, but i solved it by working through the c# model and progressively built the JSON to suit.
the full debug process started with an approach that debugged the core element. RadzenUiElement (bottom up) followed by building out the wrapper for the whole lot top down.
The JSON deserialization is failing with the exception System.StackOverflowException.
I'm trying the deserialize the following entity. Need help, why this is causing the issue.
var workingJSONString = "{\"FBTOrLeaseYear\":{\"DateFrom\":\"2019-03-02T00:00:00\",\"DateTo\":\"2020-03-01T00:00:00\"},\"Registration\":\"155SQN\",\"NovatedLeaseFortnightBenefitGroups\":[],\"NovatedLeaseAnnualBenefitGroups\":[]}";
var exceptionJSONString = "{\"FBTOrLeaseYear\":{\"DateFrom\":\"2019-03-02T00:00:00\",\"DateTo\":\"2020-03-01T00:00:00\"},\"Registration\":\"155SQN\",\"NovatedLeaseFortnightBenefitGroups\":[{\"BenefitGroupID\":1,\"BenefitGroupName\":\"Fuel\",\"TotalAnnualBudgetAmount\":4992.0000,\"TotalFortnightBudgetAmount\":192.0000,\"TotalSpentToDate\":3327.43,\"TotalFortnightSpent\":141.59276595744680851063829788,\"TotalProjAnnualAmount\":3681.4119148936170212765957447,\"TotalVariationAmount\":1310.5880851063829787234042553,\"AverageSpentPercentage\":14.645499465811966666666666667,\"NovatedLeaseBudgetSpentDataForBenefits\":[]}],\"NovatedLeaseAnnualBenefitGroups\":[]}";
Test.Entities.NovatedLeaseBenefitsBudgetSpentFBTYear novatedLeaseBenefitsBudgetSpentFBTYearResponse = new Test.Entities.NovatedLeaseBenefitsBudgetSpentFBTYear();
novatedLeaseBenefitsBudgetSpentFBTYearResponse = JsonConvert.DeserializeObject<Test.Entities.NovatedLeaseBenefitsBudgetSpentFBTYear>(exceptionJSONString); // Exception is thrown here
Entities:
On deserialization of the "Test.Entities.NovatedLeaseBenefitsBudgetSpentFBTYear" entity,
I'm getting an exception "System.StackOverflowException". Can one please help me why the deserizarion is failing for this JSON.
public class NovatedLeaseBenefitsBudgetSpentFBTYear
{
public FBTOrLeaseYear FBTOrLeaseYear { get; set; }
public string Registration { get; set; }
public List<NovatedLeaseBenefitGroup> NovatedLeaseFortnightBenefitGroups { get; set; }
public List<NovatedLeaseBenefitGroup> NovatedLeaseAnnualBenefitGroups { get; set; }
}
public class NovatedLeaseBenefitGroup
{
public int BenefitGroupID { get; set; }
public string BenefitGroupName { get; set; }
public double TotalAnnualBudgetAmount { get; set; }
public double TotalFortnightBudgetAmount { get; set; }
public double TotalSpentToDate { get; set; }
public double TotalFortnightSpent { get; set; }
public double TotalProjAnnualAmount { get; set; }
public double TotalVariationAmount { get; set; }
public double AverageSpentPercentage { get; set; }
public List<NovatedLeaseBudgetSpentDataForBenefit> NovatedLeaseBudgetSpentDataForBenefits { get; set; }
}
public class NovatedLeaseBudgetSpentDataForBenefit
{
public int BenefitId { get; set; }
public string BenefitName { get; set; }
public double AnnualBudgetAmount { get; set; }
public double FortnightBudgetAmount { get; set; }
public double SpentToDate { get; set; }
public double FortnightSpent { get; set; }
public double ProjAnnualAmount { get; set; }
public double VariationAmount { get; set; }
public double SpentPercentage { get; set; }
}
public class FBTOrLeaseYear
{
public string DateFrom { get; set; }
public string DateTo { get; set; }
}
been a while since I posted here. I'm working on an app and need to fetch statistics for a particular video using JSON (C#, UWP).
I already have the statistics as a JSON string but can't seem to parse them properly using Newtonsoft. The value always comes back null. This is my code:
var url = "https://www.googleapis.com/youtube/v3/videos?id=" + videoId + "&key=" + cl.googleAPIKey + "&part=snippet,contentDetails,statistics,status";
var http = new HttpClient();
var response = await http.GetStringAsync(url);
var statistics = JsonConvert.DeserializeObject<Statistics>(response);
string totalViews = statistics.viewCount;
The classes generated by Json2CSharp are:
public class PageInfo
{
public int totalResults { get; set; }
public int resultsPerPage { get; set; }
}
public class Default
{
public string url { get; set; }
public int width { get; set; }
public int height { get; set; }
}
public class Medium
{
public string url { get; set; }
public int width { get; set; }
public int height { get; set; }
}
public class High
{
public string url { get; set; }
public int width { get; set; }
public int height { get; set; }
}
public class Standard
{
public string url { get; set; }
public int width { get; set; }
public int height { get; set; }
}
public class Maxres
{
public string url { get; set; }
public int width { get; set; }
public int height { get; set; }
}
public class Thumbnails
{
public Default #default { get; set; }
public Medium medium { get; set; }
public High high { get; set; }
public Standard standard { get; set; }
public Maxres maxres { get; set; }
}
public class Localized
{
public string title { get; set; }
public string description { get; set; }
}
public class Snippet
{
public DateTime publishedAt { get; set; }
public string channelId { get; set; }
public string title { get; set; }
public string description { get; set; }
public Thumbnails thumbnails { get; set; }
public string channelTitle { get; set; }
public List<string> tags { get; set; }
public string categoryId { get; set; }
public string liveBroadcastContent { get; set; }
public Localized localized { get; set; }
}
public class ContentDetails
{
public string duration { get; set; }
public string dimension { get; set; }
public string definition { get; set; }
public string caption { get; set; }
public bool licensedContent { get; set; }
public string projection { get; set; }
}
public class Status
{
public string uploadStatus { get; set; }
public string privacyStatus { get; set; }
public string license { get; set; }
public bool embeddable { get; set; }
public bool publicStatsViewable { get; set; }
}
public class Statistics
{
public string viewCount { get; set; }
public string likeCount { get; set; }
public string dislikeCount { get; set; }
public string favoriteCount { get; set; }
public string commentCount { get; set; }
}
public class Item
{
public string kind { get; set; }
public string etag { get; set; }
public string id { get; set; }
public Snippet snippet { get; set; }
public ContentDetails contentDetails { get; set; }
public Status status { get; set; }
public Statistics statistics { get; set; }
}
public class RootObject
{
public string kind { get; set; }
public string etag { get; set; }
public PageInfo pageInfo { get; set; }
public List<Item> items { get; set; }
}
As I say the value will always come back as null regardless of the video ID.
Does anyone have any ideas?
Thanks
You are deserializing to the wrong class. Json2Csharp generated many classes, but Statistics is way down the tree. You should deserialize the RootObject instead:
var root = JsonConvert.DeserializeObject<RootObject>( response );
And then navigate to the statistics within the resulting class structure like for example:
foreach ( var statistics in root.Items.Select( i => i.Statistics) )
{
//do something
}
Found an odd issue when trying to deserialize a JSON string into a C# Object. It "seems" to perform the operation successfully (as in it does not throw any exception etc), however the outputted POCO contains does not contain any data from the JSON string, it only contains type default data (nulls,"", 0 etc). I have tried this process with other JSON and it works fine.
private string GetJson()
{
return #"{""backdrop_path"":"" / 1LrtAhWPSEetJLjblXvnaYtl7eA.jpg"",""created_by"":[{""id"":488,""name"":""Steven Spielberg"",""profile_path"":"" / pOK15UNaw75Bzj7BQO1ulehbPPm.jpg""},{""id"":31,""name"":""Tom Hanks"",""profile_path"":"" / a14CNByTYALAPSGlwlmfHILpEIW.jpg""}],""episode_run_time"":[60],""first_air_date"":""2001 - 09 - 09"",""genres"":[{""id"":28,""name"":""Action""},{""id"":12,""name"":""Adventure""},{""id"":18,""name"":""Drama""},{""id"":10752,""name"":""War""}],""homepage"":""http://www.hbo.com/band-of-brothers"",""id"":4613,""in_production"":false,""languages"":[""de"",""fr"",""lt"",""nl"",""en""],""last_air_date"":""2001-11-04"",""name"":""Band of Brothers"",""networks"":[{""id"":49,""name"":""HBO""}],""number_of_episodes"":10,""number_of_seasons"":1,""origin_country"":[""GB"",""US""],""original_language"":""en"",""original_name"":""Band of Brothers"",""overview"":""Drawn from interviews with survivors of Easy Company, as well as their journals and letters, Band of Brothers chronicles the experiences of these men from paratrooper training in Georgia through the end of the war. As an elite rifle company parachuting into Normandy early on D-Day morning, participants in the Battle of the Bulge, and witness to the horrors of war, the men of Easy knew extraordinary bravery and extraordinary fear - and became the stuff of legend. Based on Stephen E. Ambrose's acclaimed book of the same name."",""popularity"":3.435181,""poster_path"":""/bUrt6oeXd04ImEwQjO9oLjRguaA.jpg"",""production_companies"":[{""name"":""DreamWorks SKG"",""id"":27},{""name"":""HBO Films"",""id"":7429},{""name"":""DreamWorks Television"",""id"":15258}],""seasons"":[{""air_date"":null,""episode_count"":4,""id"":14071,""poster_path"":""/bMN9iiSAdnmAjflREfCCH0TTNyQ.jpg"",""season_number"":0},{""air_date"":""2001-09-09"",""episode_count"":10,""id"":14070,""poster_path"":""/15SN18OVbYt12Wzttclh51Sz9m1.jpg"",""season_number"":1}],""status"":""Ended"",""type"":""Scripted"",""vote_average"":8.5,""vote_count"":47}";
}
[TestMethod]
public void DeserializeTmdbShowData_ValidShowData_ReturnDeserializedObject()
{
//Arrange
string jsonStream = GetJson();
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
//Act
var tmdbShowDetails = jsonSerializer.Deserialize<List<TmdbShowDetailsDto>>(jsonStream);
//Assert
Assert.IsNotNull(tmdbShowDetails);
Assert.IsNotNull(tmdbShowDetails.First().backdrop_path);
}
public class TmdbShowDetailsDto
{
public string backdrop_path { get; set; }
public Created_By[] created_by { get; set; }
public int[] episode_run_time { get; set; }
public string first_air_date { get; set; }
public Genre[] genres { get; set; }
public string homepage { get; set; }
public int id { get; set; }
public bool in_production { get; set; }
public string[] languages { get; set; }
public string last_air_date { get; set; }
public string name { get; set; }
public Network[] networks { get; set; }
public int number_of_episodes { get; set; }
public int number_of_seasons { get; set; }
public string[] origin_country { get; set; }
public string original_language { get; set; }
public string original_name { get; set; }
public string overview { get; set; }
public float popularity { get; set; }
public string poster_path { get; set; }
public Production_Companies[] production_companies { get; set; }
public Season[] seasons { get; set; }
public string status { get; set; }
public string type { get; set; }
public float vote_average { get; set; }
public int vote_count { get; set; }
}
public class Created_By
{
public int id { get; set; }
public string name { get; set; }
public string profile_path { get; set; }
}
public class Genre
{
public int id { get; set; }
public string name { get; set; }
}
public class Network
{
public int id { get; set; }
public string name { get; set; }
}
public class Production_Companies
{
public string name { get; set; }
public int id { get; set; }
}
public class Season
{
public string air_date { get; set; }
public int episode_count { get; set; }
public int id { get; set; }
public string poster_path { get; set; }
public int season_number { get; set; }
}
Any ideas - Im sure I have missed something glaringly obvious but I cannot see it. Using .NET 4.5
Help appreciated.
Cheers
I used http://json2csharp.com/, and the code is like this, so you should look at it.
public class Poster
{
public string full { get; set; }
public string medium { get; set; }
public string thumb { get; set; }
}
public class Fanart
{
public string full { get; set; }
public string medium { get; set; }
public string thumb { get; set; }
}
public class Images
{
public Poster poster { get; set; }
public Fanart fanart { get; set; }
}
public class Ids
{
public int trakt { get; set; }
public string slug { get; set; }
public int tvdb { get; set; }
public string imdb { get; set; }
public int tmdb { get; set; }
public int tvrage { get; set; }
}
public class Show
{
public string title { get; set; }
public string overview { get; set; }
public int year { get; set; }
public string status { get; set; }
public Images images { get; set; }
public Ids ids { get; set; }
}
public class Poster2
{
public string full { get; set; }
public string medium { get; set; }
public string thumb { get; set; }
}
public class Fanart2
{
public string full { get; set; }
public string medium { get; set; }
public string thumb { get; set; }
}
public class Images2
{
public Poster2 poster { get; set; }
public Fanart2 fanart { get; set; }
}
public class Ids2
{
public int trakt { get; set; }
public string slug { get; set; }
public string imdb { get; set; }
public int tmdb { get; set; }
}
public class Movie
{
public string title { get; set; }
public string overview { get; set; }
public int year { get; set; }
public Images2 images { get; set; }
public Ids2 ids { get; set; }
}
public class Headshot
{
public object full { get; set; }
public object medium { get; set; }
public object thumb { get; set; }
}
public class Images3
{
public Headshot headshot { get; set; }
}
public class Ids3
{
public int trakt { get; set; }
public string slug { get; set; }
public string imdb { get; set; }
public int tmdb { get; set; }
public int tvrage { get; set; }
}
public class Person
{
public string name { get; set; }
public Images3 images { get; set; }
public Ids3 ids { get; set; }
}
public class RootObject
{
public string type { get; set; }
public object score { get; set; }
public Show show { get; set; }
public Movie movie { get; set; }
public Person person { get; set; }
}
You can use Paste-Special Feature in your VS-IDE Paster JSON as Classes
public class Rootobject
{
public Class1[] Property1 { get; set; }
}
public class Class1
{
public string type { get; set; }
public object score { get; set; }
public Show show { get; set; }
public Movie movie { get; set; }
public Person person { get; set; }
}
public class Show
{
public string title { get; set; }
public string overview { get; set; }
public int year { get; set; }
public string status { get; set; }
public Images images { get; set; }
public Ids ids { get; set; }
}
public class Images
{
public Poster poster { get; set; }
public Fanart fanart { get; set; }
}
public class Poster
{
public string full { get; set; }
public string medium { get; set; }
public string thumb { get; set; }
}
public class Fanart
{
public string full { get; set; }
public string medium { get; set; }
public string thumb { get; set; }
}
public class Ids
{
public int trakt { get; set; }
public string slug { get; set; }
public int tvdb { get; set; }
public string imdb { get; set; }
public int tmdb { get; set; }
public int tvrage { get; set; }
}
public class Movie
{
public string title { get; set; }
public string overview { get; set; }
public int year { get; set; }
public Images1 images { get; set; }
public Ids1 ids { get; set; }
}
public class Images1
{
public Poster1 poster { get; set; }
public Fanart1 fanart { get; set; }
}
public class Poster1
{
public string full { get; set; }
public string medium { get; set; }
public string thumb { get; set; }
}
public class Fanart1
{
public string full { get; set; }
public string medium { get; set; }
public string thumb { get; set; }
}
public class Ids1
{
public int trakt { get; set; }
public string slug { get; set; }
public string imdb { get; set; }
public int tmdb { get; set; }
}
public class Person
{
public string name { get; set; }
public Images2 images { get; set; }
public Ids2 ids { get; set; }
}
public class Images2
{
public Headshot headshot { get; set; }
}
public class Headshot
{
public object full { get; set; }
public object medium { get; set; }
public object thumb { get; set; }
}
public class Ids2
{
public int trakt { get; set; }
public string slug { get; set; }
public string imdb { get; set; }
public int tmdb { get; set; }
public int tvrage { get; set; }
}
Look like you JSON string is not in correct format that you are trying to deserialize. For example i have not find show property in the C# class but it present in JSON.
So this issue I couldn't figure out in the night or early in the morning - it took me till this afternoon until I realised that I was had the wrong JSON!!, so no wonder it wasn't working! I got mixed up with a few different apis that provided JSON. Thanks to those who had pointed out that the class looks wrong, made me double check my code and realise the simplicity of this issue. Kinda needed some rubber ducking to spot the problem. Cheers
I am trying to parse JSON response so I created some classes.
Actually I want Leg and Flight class element value. I am trying to get those element value from RootObject but I don't know how to do this. I googled but I am little bit confuse.
I paste my JSON respose , Classes !!
JSON Response :
http://pastebin.com/fjjLxkd2
Classes :
public class Detail
{
}
public class Airport
{
public string kind { get; set; }
public string code { get; set; }
public string city { get; set; }
public string name { get; set; }
}
public class City
{
public string kind { get; set; }
public string code { get; set; }
public string name { get; set; }
}
public class Aircraft
{
public string kind { get; set; }
public string code { get; set; }
public string name { get; set; }
}
public class Tax
{
public string kind { get; set; }
public string id { get; set; }
public string name { get; set; }
}
public class Carrier
{
public string kind { get; set; }
public string code { get; set; }
public string name { get; set; }
}
public class Data
{
public string kind { get; set; }
public List<Airport> airport { get; set; }
public List<City> city { get; set; }
public List<Aircraft> aircraft { get; set; }
public List<Tax> tax { get; set; }
public List<Carrier> carrier { get; set; }
}
public class Flight
{
public string carrier { get; set; }
public string number { get; set; }
}
public class Leg
{
public string kind { get; set; }
public string id { get; set; }
public string aircraft { get; set; }
public string arrivalTime { get; set; }
public string departureTime { get; set; }
public string origin { get; set; }
public string destination { get; set; }
public string originTerminal { get; set; }
public int duration { get; set; }
public int onTimePerformance { get; set; }
public int mileage { get; set; }
public string meal { get; set; }
public bool secure { get; set; }
public string destinationTerminal { get; set; }
public string operatingDisclosure { get; set; }
}
public class Segment
{
public string kind { get; set; }
public int duration { get; set; }
public Flight flight { get; set; }
public string id { get; set; }
public string cabin { get; set; }
public string bookingCode { get; set; }
public int bookingCodeCount { get; set; }
public string marriedSegmentGroup { get; set; }
public List<Leg> leg { get; set; }
public int connectionDuration { get; set; }
}
public class Slouse
{
public string kind { get; set; }
public int duration { get; set; }
public List<Segment> segment { get; set; }
}
public class Fare
{
public string kind { get; set; }
public string id { get; set; }
public string carrier { get; set; }
public string origin { get; set; }
public string destination { get; set; }
public string basisCode { get; set; }
}
public class BagDescriptor
{
public string kind { get; set; }
public string commercialName { get; set; }
public int count { get; set; }
public string subcode { get; set; }
public List<string> description { get; set; }
}
public class FreeBaggageOption
{
public string kind { get; set; }
public List<BagDescriptor> bagDescriptor { get; set; }
public int pieces { get; set; }
}
public class SegmentPricing
{
public string kind { get; set; }
public string fareId { get; set; }
public string segmentId { get; set; }
public List<FreeBaggageOption> freeBaggageOption { get; set; }
}
public class Passengers
{
public string kind { get; set; }
public int adultCount { get; set; }
}
public class Tax2
{
public string kind { get; set; }
public string id { get; set; }
public string chargeType { get; set; }
public string code { get; set; }
public string country { get; set; }
public string salePrice { get; set; }
}
public class Pricing
{
public string kind { get; set; }
public List<Fare> fare { get; set; }
public List<SegmentPricing> segmentPricing { get; set; }
public string baseFareTotal { get; set; }
public string saleFareTotal { get; set; }
public string saleTaxTotal { get; set; }
public string saleTotal { get; set; }
public Passengers passengers { get; set; }
public List<Tax2> tax { get; set; }
public string fareCalculation { get; set; }
public string latestTicketingTime { get; set; }
public string ptc { get; set; }
}
public class TripOption
{
public string kind { get; set; }
public string saleTotal { get; set; }
public string id { get; set; }
public List<Slouse> slice { get; set; }
public List<Pricing> pricing { get; set; }
}
public class Trips
{
public string kind { get; set; }
public string requestId { get; set; }
public Data data { get; set; }
public List<TripOption> tripOption { get; set; }
}
public class RootObject
{
public string kind { get; set; }
public Trips trips { get; set; }
}
Code :
var obj0 = JsonConvert.DeserializeObject<RootObject>(responsedata);
Here I got only Trip class element . I want the Leg and Flight class element.
If you want to find information for a specific leg, you need to use Linq to traverse the tree. For example, if you just know the leg id, you could do something like this:
var allLegs = obj0.trips.tripOption.SelectMany(to => to.slice.SelectMany(sl => sl.segment.Select(sg => sg.leg)));
var leg = allLegs.FirstOrDefault(l => l.id == "yourId");
The query for retrieving a flight would be similar. You could also filter by tripOption id to get a specific tripOption and then retrieve flights or legs that are associated with it.