I'm trying to grab the high and low from this api, I am able to get the High, but can't figure out what to do to get the Low, which is the second occurring item with the name "fahrenheit", how could I do this using the same method I used for getting the High?
if (xmlForecast.Name == "fahrenheit" && i == 0)
{
i++;
xmlHigh = xmlForecast.ReadString();
}
Since you want solution using XML response, here it is:
First, you'll need to create classes which will represent XML response.
[XmlRoot("response")]
public class Response
{
[XmlElement("version")]
public string Version { get; set; }
[XmlElement("termsofService")]
public string TermsOfService { get; set; }
[XmlElement("features")]
public Features Features { get; set; }
[XmlElement("forecast")]
public Forecast Forecast { get; set; }
}
public class Features
{
[XmlElement("forecast")]
public int Forecast { get; set; }
}
public class Forecast
{
[XmlElement("txt_forecast")]
public TxtForecast TxtForecast { get; set; }
[XmlElement("simpleforecast")]
public SimpleForecast SimpleForecast { get; set; }
}
public class TxtForecast
{
[XmlElement("date")]
public string Date { get; set; }
[XmlArray("forecastdays")]
[XmlArrayItem("forecastday")]
public List<ForecastDay> ForecastDays { get; set; }
}
public class ForecastDay
{
[XmlElement("period")]
public int Period { get; set; }
[XmlElement("icon")]
public string Icon { get; set; }
[XmlElement("icon_url")]
public string IconUrl { get; set; }
[XmlElement("title")]
public string Title { get; set; }
[XmlElement("fcttext")]
public string FctText { get; set; }
[XmlElement("fcttext_metric")]
public string FctTextMetric { get; set; }
[XmlElement("pop")]
public string Pop { get; set; }
}
public class SimpleForecast
{
[XmlArray("forecastdays")]
[XmlArrayItem("forecastday")]
public List<ForecastDay2> ForecastDays { get; set; }
}
public class ForecastDay2
{
[XmlElement("date")]
public Date Date { get; set; }
[XmlElement("period")]
public int Period { get; set; }
[XmlElement("high")]
public High High { get; set; }
[XmlElement("low")]
public Low Low { get; set; }
[XmlElement("conditions")]
public string Conditions { get; set; }
[XmlElement("icon")]
public string Icon { get; set; }
[XmlElement("icon_url")]
public string IconUrl { get; set; }
[XmlElement("skyicon")]
public string SkyIcon { get; set; }
[XmlElement("pop")]
public int Pop { get; set; }
[XmlElement("qpf_allday")]
public QpfAllday QpfAllDay { get; set; }
[XmlElement("qpf_day")]
public QpfDay QpfDay { get; set; }
[XmlElement("qpf_night")]
public QpfNight QpfNight { get; set; }
[XmlElement("snow_allday")]
public SnowAllday SnowAllday { get; set; }
[XmlElement("snow_day")]
public SnowDay SnowDay { get; set; }
[XmlElement("snow_night")]
public SnowNight SnowNight { get; set; }
[XmlElement("maxwind")]
public MaxWind MaxWind { get; set; }
[XmlElement("avewind")]
public AveWind AveWind { get; set; }
[XmlElement("avehumidity")]
public int AveHumidity { get; set; }
[XmlElement("maxhumidity")]
public int MaxHumidity { get; set; }
[XmlElement("minhumidity")]
public int MinHumidity { get; set; }
}
public class Date
{
[XmlElement("epoch")]
public string Epoch { get; set; }
[XmlElement("pretty")]
public string Pretty { get; set; }
[XmlElement("day")]
public int Day { get; set; }
[XmlElement("month")]
public int Month { get; set; }
[XmlElement("year")]
public int Year { get; set; }
[XmlElement("yday")]
public int Yesterday { get; set; }
[XmlElement("hour")]
public int Hour { get; set; }
[XmlElement("min")]
public string Min { get; set; }
[XmlElement("sec")]
public int Sec { get; set; }
[XmlElement("isdst")]
public string Isdst { get; set; }
[XmlElement("monthname")]
public string MonthName { get; set; }
[XmlElement("monthname_short")]
public string MonthNameShort { get; set; }
[XmlElement("weekday_short")]
public string WeekdayShort { get; set; }
[XmlElement("weekday")]
public string Weekday { get; set; }
[XmlElement("ampm")]
public string AmPM { get; set; }
[XmlElement("tz_short")]
public string TzShort { get; set; }
[XmlElement("tz_long")]
public string TzLong { get; set; }
}
public class High
{
[XmlElement("fahrenheit")]
public string Fahrenheit { get; set; }
[XmlElement("celsius")]
public string Celsius { get; set; }
}
public class Low
{
[XmlElement("fahrenheit")]
public string Fahrenheit { get; set; }
[XmlElement("celsius")]
public string Celsius { get; set; }
}
public class QpfAllday
{
[XmlElement("#in")]
public double Inches { get; set; }
[XmlElement("mm")]
public int Milimeters { get; set; }
}
public class QpfDay
{
[XmlElement("#in")]
public double Inches { get; set; }
[XmlElement("mm")]
public int Milimeters { get; set; }
}
public class QpfNight
{
[XmlElement("#in")]
public double Inches { get; set; }
[XmlElement("mm")]
public int Milimeters { get; set; }
}
public class SnowAllday
{
[XmlElement("#in")]
public double Inches { get; set; }
[XmlElement("cm")]
public double Centimeters { get; set; }
}
public class SnowDay
{
[XmlElement("#in")]
public double Inches { get; set; }
[XmlElement("cm")]
public double Centimeters { get; set; }
}
public class SnowNight
{
[XmlElement("#in")]
public double Inches { get; set; }
[XmlElement("cm")]
public double Centimeters { get; set; }
}
public class MaxWind
{
[XmlElement("mph")]
public int Mph { get; set; }
[XmlElement("kph")]
public int Kph { get; set; }
[XmlElement("dir")]
public string Direction { get; set; }
[XmlElement("degrees")]
public int Degrees { get; set; }
}
public class AveWind
{
[XmlElement("mph")]
public int Mph { get; set; }
[XmlElement("kph")]
public int Kph { get; set; }
[XmlElement("dir")]
public string Direction { get; set; }
[XmlElement("degrees")]
public int Degrees { get; set; }
}
Secondly, you need to deserialize XML into Response
using (HttpClient client = new HttpClient())
{
using (var stream = await client.GetStreamAsync("http://api.wunderground.com/api/ea4bb7e7839782da/forecast/q/CA/San_Francisco.xml"))
{
var serializer = new XmlSerializer(typeof(Response));
var response = (Response)serializer.Deserialize(stream);
var simpleForecast = response.Forecast.SimpleForecast;
var forecastDays = simpleForecast.ForecastDays;
var latestForecastDay = forecastDays.Last();
var latestHighFahrenheit = latestForecastDay.High.Fahrenheit;
var latestLowFahrenheit = latestForecastDay.Low.Fahrenheit;
}
}
I am using XmlSerializer but you can also use DataContractSerializer which is newer. If you decide to use DataContractSerializer keep in mind that you'll need to replace XmlElement attributes with DataContract and DataMember.
Note: I've intentionally added few unnecessary steps and variable declarations, so you can see clearly what's going on here.
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 am having difficulty replacing the Dark Sky API with Open weather. GPS Location works and is received through another azure function.The Dark Sky Api call still works too. It might be something little but I'm not sure what's wrong. The only significant difference from the Dark Sky Api is the data model. Yet, Postman keeps responding with null values.
Postman response:
{
"id": 0,
"main": null,
"description": null,
"icon": null
}
public interface IWeatherService
{
Task<Weather> GetWeatherAsync(double latitude, double longitude);
}
public class WeatherService : IWeatherService
{
private readonly HttpClient _client;
private readonly ILogger<IWeatherService> _logger;
public WeatherService(HttpClient client, ILogger<IWeatherService> logger)
{
_client = client;
_client.BaseAddress = new Uri("https://api.openweathermap.org/data/2.5/weather?");
_client.Timeout = TimeSpan.FromSeconds(10);
_logger = logger;
}
public async Task<Weather> GetWeatherAsync(double latitude, double longitude)
{
Weather retval = null;
try
{
if (latitude.Equals(0) || longitude.Equals(0))
return null;
var key = "HIDDEN";
// var API = Environment.GetEnvironmentVariable("WeatherKey");
var exclude = "minutely,hourly,daily,alerts";
var units = "imperial";
var requestUrl = $"&lat={latitude}&lon={longitude}&exclude={exclude}&units={units}&appid={key}";
var response = await _client.GetAsync(requestUrl);
var result = response.Content.ReadAsStringAsync().Result;
var weather = JsonConvert.DeserializeObject<Weather>(result);
retval = weather;
//}
//handler.Dispose();
}
catch (Exception ex)
{
_logger.LogError(ex, $"Error in {nameof(GetWeatherAsync)}");
}
return retval;
}
The new model:
namespace WeatherWebAPI.Models
{
using Newtonsoft.Json;yy
public partial class Temperatures
{
[JsonProperty("coord")]
public Coord Coord { get; set; }
[JsonProperty("weather")]
public Weather[] Weather { get; set; }
[JsonProperty("base")]
public string Base { get; set; }
[JsonProperty("main")]
public Main Main { get; set; }
[JsonProperty("visibility")]
public long Visibility { get; set; }
[JsonProperty("wind")]
public Wind Wind { get; set; }
[JsonProperty("clouds")]
public Clouds Clouds { get; set; }
[JsonProperty("dt")]
public long Dt { get; set; }
[JsonProperty("sys")]
public Sys Sys { get; set; }
[JsonProperty("timezone")]
public long Timezone { get; set; }
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("cod")]
public long Cod { get; set; }
}
public partial class Clouds
{
[JsonProperty("all")]
public long All { get; set; }
}
public partial class Coord
{
[JsonProperty("lon")]
public double Lon { get; set; }
[JsonProperty("lat")]
public double Lat { get; set; }
}
public partial class Main
{
[JsonProperty("temp")]
public double Temp { get; set; }
[JsonProperty("feels_like")]
public double FeelsLike { get; set; }
[JsonProperty("temp_min")]
public double TempMin { get; set; }
[JsonProperty("temp_max")]
public double TempMax { get; set; }
[JsonProperty("pressure")]
public long Pressure { get; set; }
[JsonProperty("humidity")]
public long Humidity { get; set; }
}
public partial class Sys
{
[JsonProperty("type")]
public long Type { get; set; }
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("message")]
public double Message { get; set; }
[JsonProperty("country")]
public string Country { get; set; }
[JsonProperty("sunrise")]
public long Sunrise { get; set; }
[JsonProperty("sunset")]
public long Sunset { get; set; }
}
public partial class Weather
{
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("main")]
public string Main { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("icon")]
public string Icon { get; set; }
}
public partial class Wind
{
[JsonProperty("speed")]
public double Speed { get; set; }
[JsonProperty("deg")]
public long Deg { get; set; }
}
}
The Old Model:
namespace WeatherWebAPI.Models
{
#pragma warning disable IDE1006 // Naming Styles
public class Response
{
public double latitude { get; set; }
public double longitude { get; set; }
public string timezone { get; set; }
public DataPoint currently { get; set; }
}
public class DataPoint
{
public double apparentTemperatureHigh { get; set; }
public string apparentTemperatureHighTime { get; set; }
public double apparentTemperatureLow { get; set; }
public string apparentTemperatureLowTime { get; set; }
public double apparentTemperatureMax { get; set; }
public string apparentTemperatureMaxTime { get; set; }
public double apparentTemperatureMin { get; set; }
public string apparentTemperatureMinTime { get; set; }
public long time { get; set; }
public string summary { get; set; }
public string icon { get; set; }
public string sunriseTime { get; set; }
public string sunsetTime { get; set; }
public double nearestStormDistance { get; set; }
public double nearestStormBearing { get; set; }
public double precipIntensity { get; set; }
public double precipIntensityMax { get; set; }
public string precipIntensityMaxTime { get; set; }
public string precipIntensityError { get; set; }
public double preciProbability { get; set; }
public string precipType { get; set; }
public double temperature { get; set; }
public double temperatureHigh { get; set; }
public string temperatureHighTime { get; set; }
public double temperatureLow { get; set; }
public string temperatureLowTime { get; set; }
public double temperatureMax { get; set; }
public string temperatureMaxTime { get; set; }
public double temperatureMin { get; set; }
public string temperatureMinTime { get; set; }
public double apparentTemperature { get; set; }
public double dewPoint { get; set; }
public double humidity { get; set; }
public double pressure { get; set; }
public double windSpeed { get; set; }
public double windGust { get; set; }
public string windGustTime { get; set; }
public double windBearing { get; set; }
public double cloudCover { get; set; }
public double uvIndex { get; set; }
public double uvIndexTime { get; set; }
public double visibility { get; set; }
public double ozone { get; set; }
public double moonPhase { get; set; }
}
#pragma warning restore IDE1006 // Naming Styles
}
I'm faced wiht an error, and I don't know how to correct it. I don't understand why it comes.
System.FormatException: Index (zero based) must be greater than or equal to zero and less than the size of the argument list.
The exception comes when I try to deserialize a JSON into objects that I created. (The second line code is throwing the exception)
List<Connection> connections = new List<Connection>();
var root = JsonConvert.DeserializeObject<RootObject2>(content);
connections = root.connections;
Here is the JSON that I want to use:
http://transport.opendata.ch/v1/connections?from=lausanne&to=fribourg
And here are my objects:
public class RootObject2
{
public List<Connection> connections { get; set; }
}
public class Connection
{
public Stop from { get; set; }
public Stop to { get; set; }
public string duration { get; set; }
public int? transfers { get; set; }
public Service service { get; set; }
public List<string> products { get; set; }
public int? capacity1st { get; set; }
public int? capacity2nd { get; set; }
public List<Section> sections { get; set; }
}
public class Stop
{
public Station station { get; set; }
public DateTime arrival { get; set; }
public int? arrivalTimestamp { get; set; }
public string departure { get; set; }
public int? departureTimestamp { get; set; }
public int? delay { get; set; }
public string platform { get; set; }
public Prognosis prognosis { get; set; }
public string realtimeAvailability {get; set;}
public Station location { get; set; }
}
public class Station
{
public string id { get; set; }
public string name { get; set; }
public int? score { get; set; }
public Coordinate coordinate { get; set; }
public double? distance { get; set; }
}
public class Service
{
public string regular { get; set; }
public string irregular { get; set; }
}
public class Section
{
public Journey journey { get; set; }
public Walk walk { get; set; }
public Stop departure { get; set; }
public Stop arrival { get; set; }
}
public class Journey
{
public string name { get; set; }
public string category { get; set; }
public string subcategory { get; set; }
public int? categoryCode { get; set; }
public string number { get; set; }
public string #operator { get; set; }
public string to { get; set; }
public List<Stop> passList { get; set; }
public int? capacity1st { get; set; }
public int? capacity2nd { get; set; }
}
public class Walk
{
public string duration { get; set; }
}
public class Prognosis
{
public string platform { get; set; }
public string arrival { get; set; }
public string departure { get; set; }
public int? capacity1st { get; set; }
public int? capacity2nd { get; set; }
}
public class Coordinate
{
public string type { get; set; }
public double x { get; set; }
public double y { get; set; }
}
The deserialization is on a try and catch block, and nothing is catched.
Also I am doing this on Android.
Based on json data.
Arrival property in Stop class should be DateTime?.
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;
}
}