🌐 Networking & APIs
Parsing JSON with System.Text.Json
Deserializing responses, JsonPropertyName, error handling.

System.Text.Json

csharp
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

csharp
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

csharp
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
Lesson 22 of 30Networking & APIs
← Previous Next Lesson →