I have a JSON content as
[{
"LocalObservationDateTime": "2018-04-23T08:10:00+05:00",
"EpochTime": 1524453000,
"WeatherText": "Sunny",
"WeatherIcon": 1,
"IsDayTime": true,
"Temperature": {
"Metric": {
"Value": 29.6,
"Unit": "C",
"UnitType": 17
},
"Imperial": {
"Value": 85.0,
"Unit": "F",
"UnitType": 18
}
},
"MobileLink": "http://m.accuweather.com/en/pk/jamaluddinwali/259991/current-weather/259991?lang=en-us",
"Link": "http://www.accuweather.com/en/pk/jamaluddinwali/259991/current-weather/259991?lang=en-us"
}]
my class to handle this content is as follow:
class AccuWeather
{
public class RootObject
{
public Class1[] Property1 { get; set; }
}
public class Class1
{
public DateTime LocalObservationDateTime { get; set; }
public int EpochTime { get; set; }
public string WeatherText { get; set; }
public int WeatherIcon { get; set; }
public bool IsDayTime { get; set; }
public Temperature Temperature { get; set; }
public string MobileLink { get; set; }
public string Link { get; set; }
}
I just tried to deserialize this content by the following code snippet in C#:
private AccuWeather.RootObject Parse_A(string targetURI)
{
Uri uri = new Uri(targetURI);
var webRequest = WebRequest.Create(uri);
WebResponse response = webRequest.GetResponse();
AccuWeather.RootObject wUData = null;
try
{
using (var streamReader = new StreamReader(response.GetResponseStream()))
{
var responseData = streamReader.ReadToEnd();
// if you want all the "raw data" as a string
// just use: responseData.ToString()
wUData = JsonConvert.DeserializeObject<AccuWeather.RootObject<Class1>>(responseData);
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
return wUData;
}//completed
I am not sure enough that this is the proper and efficient way to deserialize JSON content. Can anybody provide some detail information on best practices in this case? Any help is appreciated in advance!
You can also use .NET dynamics for this e.g
var json = @"[{""LocalObservationDateTime"": ""2018-04-23T08:10:00+05:00"",
""EpochTime"": 1524453000,
""WeatherText"": ""Sunny"",
""WeatherIcon"": 1,
""IsDayTime"": true,
""Temperature"": {
""Metric"": {
""Value"": 29.6,
""Unit"": ""C"",
""UnitType"": 17
},
""Imperial"": {
""Value"": 85.0,
""Unit"": ""F"",
""UnitType"": 18
}
},
""MobileLink"": ""http://m.accuweather.com/en/pk/jamaluddinwali/259991/current-weather/259991?lang=en-us"",
""Link"": ""http://www.accuweather.com/en/pk/jamaluddinwali/259991/current-weather/259991?lang=en-us""
}]";
dynamic accuWeatherResp = JArray.Parse(json);
if (accuWeatherResp.Count == 0)
{
Console.WriteLine("Response is Empty");
return;
}
dynamic weather = accuWeatherResp[0];
if (weather != null)
{
Console.WriteLine("Observation time: {0:s} Weather: {1}, Temperature: {2: 0.0} °C", weather.LocalObservationDateTime, weather.WeatherText, weather.Temperature.Metric.Value);
}