Skip to content

Commit aaefa2b

Browse files
committed
Implement json & xml weather data parsers
1 parent 823eae0 commit aaefa2b

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
using System.Text.Json;
2+
using RealTimeWeatherMonitoringApp.Application.Interfaces;
3+
using RealTimeWeatherMonitoringApp.Domain.Models;
4+
5+
namespace RealTimeWeatherMonitoringApp.Infrastructure.Parsers;
6+
7+
public class WeatherDataJsonParser : IParsingStrategy<WeatherData>
8+
{
9+
public bool TryParse(string input, out WeatherData? result)
10+
{
11+
try
12+
{
13+
result = JsonSerializer.Deserialize<WeatherData>(input);
14+
return result != null;
15+
}
16+
catch (JsonException)
17+
{
18+
result = null;
19+
return false;
20+
}
21+
}
22+
}
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
using System.Xml.Linq;
2+
using RealTimeWeatherMonitoringApp.Application.Interfaces;
3+
using RealTimeWeatherMonitoringApp.Domain.Models;
4+
5+
namespace RealTimeWeatherMonitoringApp.Infrastructure.Parsers;
6+
7+
public class WeatherDataXmlParser : IParsingStrategy<WeatherData>
8+
{
9+
public bool TryParse(string input, out WeatherData? result)
10+
{
11+
result = null;
12+
if (string.IsNullOrWhiteSpace(input)) return false;
13+
14+
try
15+
{
16+
var doc = XDocument.Parse(input);
17+
18+
var weatherDataElement = doc.Element("WeatherData");
19+
if (weatherDataElement == null) return false;
20+
21+
var locationElement = weatherDataElement.Element("Location");
22+
var temperatureElement = weatherDataElement.Element("Temperature");
23+
var humidityElement = weatherDataElement.Element("Humidity");
24+
25+
if (locationElement == null || temperatureElement == null || humidityElement == null)
26+
return false;
27+
28+
result = new WeatherData(
29+
location: locationElement.Value,
30+
temperature: double.Parse(temperatureElement.Value),
31+
humidity: double.Parse(humidityElement.Value));
32+
return true;
33+
}
34+
catch (Exception)
35+
{
36+
result = null;
37+
return false;
38+
}
39+
}
40+
}

0 commit comments

Comments
 (0)