Deserializing responses, JsonPropertyName, error handling.
System.Text.Json
public class WeatherResponse
{
[JsonPropertyName("city_name")]
public string CityName { get; set; }
[JsonPropertyName("temp_c")]
public double TemperatureC { get; set; }
[JsonPropertyName("conditions")]
public List<Condition> Conditions { get; set; }
}
Serialization Options
var options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
WriteIndented = true,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
};
var weather = JsonSerializer.Deserialize<WeatherResponse>(json, options);
var json = JsonSerializer.Serialize(weather, options);
Safe Deserialization Helper
public static T? TryDeserialize<T>(string json)
{
try { return JsonSerializer.Deserialize<T>(json); }
catch { return default; }
}
Key Takeaways
System.Text.Json is built into .NET — fast, no extra package needed
[JsonPropertyName] maps JSON snake_case to C# PascalCase automatically
PropertyNameCaseInsensitive makes deserialization resilient to casing differences
Always wrap deserialization in try/catch — malformed JSON is common in production