HandlingJson2 - lucyberryhub/WPF.Tutorial GitHub Wiki

๐Ÿ“ Lucy Berry's Cutie JSON Magic Tutorial! ๐ŸŒธโœจ

๐Ÿ’– Welcome, sweet coder! Today, Lucy Berry is going to teach you how to update and remove data in a JSON file using a super cute method! ๐ŸŒท๐Ÿญ

๐Ÿ’ก We'll be learning how to:
โœ” Find a berry item in the JSON using a condition (predicate).
โœ” Update just the right details while keeping everything else unchanged.
โœ” Remove berry items if they are no longer needed.
โœ” Add a new berry if it doesnโ€™t exist!

So grab a cup of strawberry milk ๐Ÿ“๐Ÿฅ›, and let's get coding in the cutest way possible! ๐Ÿ’•


๐Ÿ“ Step 1: The Magical Update Method! โœจ

๐ŸŽ€ Update or Add a Berry in the JSON Garden!

Lucy Berry's UpdateBerryJsonFile method finds a berry ๐ŸŒท in your JSON file by its name and updates only the juicy parts while keeping the other details sweet! ๐Ÿ˜˜

public static bool UpdateBerryJsonFile<T>(
    string berryJsonPath,         // ๐ŸŒธ The path where all the berries are stored!
    T newBerryData,               // ๐Ÿ“ The new berry details to update or add!
    Func<T, bool> findBerry,      // ๐Ÿง How to find the berry? (Predicate)
    Func<T, T> updateBerryDetails // โœจ What to update if found?
) where T : class, new()
{
    if (string.IsNullOrWhiteSpace(berryJsonPath) || !File.Exists(berryJsonPath))
        return false; // ๐Ÿšจ No berries found! (Invalid path or missing file)

    try
    {
        List<T> berryBasket;

        // ๐Ÿ“ Read all the berry data!
        using (var reader = new StreamReader(berryJsonPath))
        {
            string berryJson = reader.ReadToEnd();

            berryBasket = string.IsNullOrWhiteSpace(berryJson)
                ? new List<T>()
                : JsonConvert.DeserializeObject<List<T>>(berryJson) ?? new List<T>();
        }

        // ๐Ÿฌ Look for a matching berry!
        var berryToUpdate = berryBasket.FirstOrDefault(findBerry);
        if (berryToUpdate != null)
        {
            // ๐ŸŽ€ Update the berry details! โœจ
            berryToUpdate = updateBerryDetails(berryToUpdate);
        }
        else
        {
            // ๐Ÿ“ No matching berry? Add it fresh to the basket!
            berryBasket.Add(newBerryData);
        }

        // ๐Ÿ’พ Save our berry basket back!
        using (var writer = new StreamWriter(berryJsonPath, false, Encoding.UTF8))
        {
            writer.Write(JsonConvert.SerializeObject(berryBasket, Formatting.Indented));
        }

        return true; // ๐ŸŽ‰ Success! The berry garden is updated!
    }
    catch (JsonException ex)
    {
        throw new InvalidOperationException($"๐Ÿ’” Oops! Couldn't read the berry file: {berryJsonPath}", ex);
    }
    catch (IOException ex)
    {
        throw new InvalidOperationException($"๐Ÿšจ Couldn't access the berry file: {berryJsonPath}", ex);
    }
}

๐Ÿ“ How to Use It?

Let's say we have berry-themed colors ๐Ÿ“ in our JSON, and we want to:
๐Ÿ’– Update only the berry name if it exists.
๐Ÿ’– Add a new berry if it's missing!

Here's how we do it:

foreach (var berry in berryList)
{
    BerryJsonHelper.UpdateBerryJsonFile(
        BerryConfig.BerryGardenJsonPath, // ๐ŸŒธ JSON file location
        new BerryModel  // ๐Ÿ“ Fresh berry details if new!
        {
            Name = berry.Name,
            Type = "Strawberry",
            Color = "#FF69B4",
            Taste = "Sweet",
            Size = "Medium",
            IsRipe = true
        },
        x => x.Name == berry.Name, // ๐Ÿง Find a berry with the same name!
        x =>
        {
            x.Name = berry.Name; // ๐ŸŽ€ Only update the berry name!
            return x;
        }
    );
}

๐ŸŒทโœจ Now your berries are either updated or added if they didnโ€™t exist! ๐ŸŽ€


๐Ÿ’ Step 2: The Magical Remove Method! ๐Ÿ’”๐Ÿšฎ

๐Ÿ—‘๏ธ Say Bye-Bye to Rotten Berries!

Sometimes, we need to remove old berries from our JSON ๐Ÿ“๐Ÿšฎ. Lucy Berryโ€™s RemoveBerryFromJsonFile method finds berries and removes them like magic! ๐ŸŽฉโœจ

public static bool RemoveBerryFromJsonFile<T>(
    string berryJsonPath,   // ๐ŸŒธ The path to the berry garden!
    Func<T, bool> findBerry // ๐Ÿง Which berry should we remove?
) where T : class, new()
{
    if (string.IsNullOrWhiteSpace(berryJsonPath) || !File.Exists(berryJsonPath))
        return false; // ๐Ÿšจ No berries found!

    try
    {
        List<T> berryBasket;

        // ๐Ÿ“ Read the berry garden!
        using (var reader = new StreamReader(berryJsonPath))
        {
            string berryJson = reader.ReadToEnd();
            berryBasket = string.IsNullOrWhiteSpace(berryJson)
                ? new List<T>()
                : JsonConvert.DeserializeObject<List<T>>(berryJson) ?? new List<T>();
        }

        // ๐Ÿ—‘๏ธ Remove all matching berries!
        int removedCount = berryBasket.RemoveAll(findBerry);

        if (removedCount == 0)
            return false; // ๐Ÿšจ No matching berries found!

        // ๐Ÿ’พ Save the updated berry garden!
        using (var writer = new StreamWriter(berryJsonPath, false, Encoding.UTF8))
        {
            writer.Write(JsonConvert.SerializeObject(berryBasket, Formatting.Indented));
        }

        return true; // ๐ŸŽ‰ Success! The bad berries are gone!
    }
    catch (JsonException ex)
    {
        throw new InvalidOperationException($"๐Ÿ’” Oops! Couldn't read the berry file: {berryJsonPath}", ex);
    }
    catch (IOException ex)
    {
        throw new InvalidOperationException($"๐Ÿšจ Couldn't access the berry file: {berryJsonPath}", ex);
    }
}

๐Ÿ“ How to Use It?

Let's say we want to remove all green berries ๐Ÿ from our JSON because only pink berries are allowed ๐Ÿ’•โœจ!

BerryJsonHelper.RemoveBerryFromJsonFile<BerryModel>(
    BerryConfig.BerryGardenJsonPath, // ๐ŸŒธ JSON file location
    x => x.Color == "#008000" // ๐Ÿšจ Remove all green berries!
);

๐ŸŒทโœจ Now all green berries are removed, and only the cute pink ones remain! ๐ŸŽ€


๐ŸŽ€ Final Thoughts! ๐ŸŒธโœจ

Lucy Berry has taught you how to update, add, and remove berries from a JSON file in the cutest way possible! ๐Ÿ“๐Ÿ’–

๐ŸŽ€ Now you can:
โœ… Find berries with a condition!
โœ… Update only specific berry details!
โœ… Add new berries if theyโ€™re missing!
โœ… Remove unwanted berries!

๐Ÿ“โœจ Now go ahead and create your own berry-themed JSON system! ๐ŸŽ€
Lucy Berry is so proud of you! ๐Ÿ’•๐Ÿ’–


๐ŸŒธ Did you enjoy this tutorial? ๐ŸŒธ
๐Ÿ’– Drop a ๐ŸŒท if you love it! Let's keep coding in the cutest way possible! ๐ŸŽ€โœจ

๐Ÿ’ก Any questions? Lucy Berry is here to help! ๐Ÿ“๐ŸŒท

โš ๏ธ **GitHub.com Fallback** โš ๏ธ