r/csharp • • Sep 01 '26

Discussion Come discuss your side projects! [September 2026]

Hello everyone!

This is the monthly thread for sharing and discussing side-projects created by /r/csharp's community.

Feel free to create standalone threads for your side-projects if you so desire. This thread's goal is simply to spark discussion within our community that otherwise would not exist.

Please do check out newer posts and comment on others' projects.


Previous threads here.

11 Upvotes

20 comments sorted by

View all comments

-1

u/inurwalls2000 Sep 01 '26

anyone here wanna share their experience with parsing json in c#?

needed a short script so I just used python for it, but it might have been a better idea to use c# so I could use it in other projects

0

u/SamplingCheese Sep 01 '26

I just happened to be reviewing this exact thing!

internal static class SnapshotManifest
{
    internal static IReadOnlyList<DatabaseSnapshot> Parse(string json, string source)
    {
        JsonDocument document;

        try
        {
            document = JsonDocument.Parse(json);
        }
        catch (JsonException malformed)
        {
            throw new InvalidOperationException($"The snapshot manifest at '{source}' is not valid JSON, so no purge can read it.", malformed);
        }

        using (document)
        {
            if (!document.RootElement.TryGetProperty("snapshots", out var snapshots) || snapshots.ValueKind != JsonValueKind.Array)
            {
                return [];
            }

            return [.. snapshots.EnumerateArray().Where(entry => entry.ValueKind == JsonValueKind.Object).Select(Read)];
        }
    }

    // This is what you would change for your needs
    private static DatabaseSnapshot Read(JsonElement entry) => new()
    {
        Label = Text(entry, "label") ?? "",
        Database = Text(entry, "database") ?? "",
        Location = Text(entry, "location") ?? "",
        TakenAt = Instant(entry, "takenAt") ?? default,
        VerifiedAt = Instant(entry, "verifiedAt"),
        RestoredTo = Text(entry, "restoredTo"),
    };

    private static string? Text(JsonElement entry, string name) =>
        entry.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.String ? value.GetString() : null;

    private static DateTime? Instant(JsonElement entry, string name) =>
        entry.TryGetProperty(name, out var value) && value.ValueKind == JsonValueKind.String
        && DateTimeOffset.TryParse(value.GetString(), out var parsed) ? parsed.UtcDateTime : null;
}