【发布时间】:2020-05-12 20:12:56
【问题描述】:
我正在编写一个简单的控制台天气应用程序 (OpenWeatherMap),我想验证来自 OWM 的响应是否包含任何空属性。这是我的包含属性的类:
public class WeatherMain
{
public Coord coord { get; set; }
public List<Weather> weather { get; set; }
public Main main { get; set; }
public Wind wind { get; set; }
public Rain rain { get; set; }
public Snow snow { get; set; }
public Clouds clouds { get; set; }
public Sys sys { get; set; }
[JsonProperty("base")]
public string _base { get; set; }
public int? visibility { get; set; }
public int? timezone { get; set; }
public int? id { get; set; }
public string name { get; set; }
public int? cod { get; set; }
}
如您所见,还有一些类也包含它们自己的属性。 我想检查一下,如果这些中的任何一个基本上是空的,那么我可以在控制台中通知缺失值。现在,我使用 IF 对 WeatherMain 属性进行了一些基本检查:
public static string PrepareResponse(WeatherMain input)
{
string cityName, main, visibility, wind, clouds, rain, snow, coord;
if (input.name == null)
cityName = "City name section not found\n";
else
cityName = $"\nCity name: {input.name}\n";
if (input.main == null)
main = "Main section not found\n";
else
{
main = $"Main parameters:\n\tTemperature: {input.main.temp}C\n\t" +
$"Temperature max.: {input.main.temp_max}C\n\tTemperature min.: {input.main.temp_min}C" +
$"\n\tFeels like: {input.main.feels_like}C\n\tPressure: {input.main.pressure}hPA\n\t" +
$"Humidity: {input.main.humidity}%\n";
}
if (input.visibility == null)
visibility = "Visibility section not found\n";
else
visibility = $"Visibility: {input.visibility}m\n";
if (input.wind == null)
wind = "Wind section not found\n";
else
wind = $"Wind:\n\tSpeed: {input.wind.speed}m/s\n\tDirection: {input.wind.deg}deg\n";
if (input.clouds == null)
clouds = "Clouds section not found\n";
else
clouds = $"Clouds: {input.clouds.all}%\n";
if (input.rain == null)
rain = "Rain section not found\n";
else
rain = $"Rain: {input.rain._1h}mm\n";
if (input.snow == null)
snow = "Snow section not found\n";
else
snow = $"Snow: {input.snow._1h}mm\n";
if (input.coord == null)
coord = "Coordinates section not found\n";
else
coord = $"Coordinates:\n\tLatitude: {input.coord.lat}\n\tLongitude: {input.coord.lon}\n";
string outputString = cityName + main + visibility + wind + clouds + rain + snow + coord;
return outputString;
}
我正在考虑将这些属性放入一个集合中,并一一检查它们是否为空,并可能将值更改为字符串。 我想有更好的方法可以做到这一点。 有什么想法吗?
【问题讨论】:
-
除非您愿意创建一个
Attribute来描述每种类型的输出,否则最好的想法可能是创建一个List,其中包含用于 null 和格式化消息的 lambda,并运行List.
标签: c# json properties null