DeleteJson - lucyberryhub/WPF.Tutorial GitHub Wiki

πŸ’πŸ’– Lucy Berry’s Adorable Guide to Deleting a Cherry from a JSON File πŸ’–πŸ’

✨ Welcome, cuties! Today, we will learn how to remove a cherry (data item) from our CherryJsonFile.json using a super kawaii method! πŸŒΈπŸ’ž

You’ll also meet IHasCherryId, our magical interface that makes sure every cherry (data item) has an Id, Flavor, and SweetnessLevel! 🍬✨

Ready? Grab your strawberry milk πŸ“πŸ₯› and let’s goooooo! πŸš€πŸ’–


πŸŽ€ Step 1: Creating the Magical Interface β€˜IHasCherryId’

Before we start deleting cherries, we need to create an interface to make sure every cherry has an Id, Flavor, and SweetnessLevel! πŸ’•

public interface IHasCherryId
{
    /// πŸ’ A unique cherry ID! Every cherry must have one! πŸŽ€
    long CherryId { get; set; }

    /// πŸ“ The flavor of the cherry! (Example: "Strawberry", "Blueberry") πŸ’–
    string Flavor { get; set; }

    /// 🍬 How sweet is the cherry? ("Very Sweet", "Super Sweet", "Ultra Sweet") 🍭
    string SweetnessLevel { get; set; }
}

✨ Now, every cherry must have an Id, Flavor, and SweetnessLevel! No boring cherries allowed! πŸŽ€πŸ’ž


🍭 Step 2: Writing the Cutest β€˜RemoveCherryFromJson’ Method!

Now let’s make a super sweet method to remove a cherry from our CherryJsonFile.json! πŸ’πŸ’–

private void RemoveCherryFromJson<T>(long cherryId, string cherryJsonFilePath) where T : class, IHasCherryId
{
    if (string.IsNullOrWhiteSpace(cherryJsonFilePath) || !File.Exists(cherryJsonFilePath))
        return; // πŸ“ If the file is missing, no cherries to remove! πŸ’”

    try
    {
        List<T> cherryBasket; // πŸŽ€ A cute list of cherries! πŸ’

        // πŸ“– Read the cherry list from the JSON file πŸ“œβœ¨
        using (var reader = new StreamReader(cherryJsonFilePath))
        {
            string jsonData = reader.ReadToEnd();

            if (string.IsNullOrWhiteSpace(jsonData))
                return; // 🍬 If the file is empty, no cherries to remove! 🍭

            cherryBasket = JsonConvert.DeserializeObject<List<T>>(jsonData) ?? new List<T>();
        }

        // πŸ’ Find the cherry we want to remove! πŸ’–
        var cherryToRemove = cherryBasket.FirstOrDefault(x => x.CherryId == cherryId);
        if (cherryToRemove != null)
        {
            cherryBasket.Remove(cherryToRemove); // πŸ“ Say bye-bye to the cherry! πŸŽ€βœ¨

            // πŸŽ€ Write the new cherry list back to JSON! πŸ’
            using (var writer = new StreamWriter(cherryJsonFilePath, false, Encoding.UTF8))
            {
                writer.Write(JsonConvert.SerializeObject(cherryBasket, Formatting.Indented));
            }
        }
    }
    catch (JsonException ex)
    {
        throw new InvalidOperationException($"πŸ’” Oops! Error reading the cherry file: {cherryJsonFilePath}", ex);
    }
    catch (IOException ex)
    {
        throw new InvalidOperationException($"πŸ’” Oh no! Couldn't access the cherry file: {cherryJsonFilePath}", ex);
    }
}

πŸ’– Step 3: Understanding the Cutie Code!

πŸ“ Checking the Cherry File First!

if (string.IsNullOrWhiteSpace(cherryJsonFilePath) || !File.Exists(cherryJsonFilePath))
    return;

✨ If the file is missing, don’t do anything! No cherries, no problem! πŸ’ž


πŸ’ Reading the Cherries from the Basket!

using (var reader = new StreamReader(cherryJsonFilePath))
{
    string jsonData = reader.ReadToEnd();

    if (string.IsNullOrWhiteSpace(jsonData))
        return;

    cherryBasket = JsonConvert.DeserializeObject<List<T>>(jsonData) ?? new List<T>();
}

✨ We open the cherry basket (JSON file) and load all the cherries inside! 🍬
✨ If the basket is empty, we just stop right there! πŸ’ž


πŸŽ€ Finding & Removing the Right Cherry!

var cherryToRemove = cherryBasket.FirstOrDefault(x => x.CherryId == cherryId);
if (cherryToRemove != null)
{
    cherryBasket.Remove(cherryToRemove);

✨ We search for the cherry by CherryId and remove it from the list! πŸ’


🍭 Saving the New Cherry List!

using (var writer = new StreamWriter(cherryJsonFilePath, false, Encoding.UTF8))
{
    writer.Write(JsonConvert.SerializeObject(cherryBasket, Formatting.Indented));
}

✨ We write the updated cherry list back to the JSON file! So cute! πŸŽ€πŸ’–


🌸 Step 4: Testing with a Sample Cherry Class!

Now, let’s create a cutie cherry class that follows the IHasCherryId rules! πŸ’–

public class Cherry : IHasCherryId
{
    public long CherryId { get; set; }
    public string Flavor { get; set; }
    public string SweetnessLevel { get; set; }
}

And now, let’s remove a cherry from the JSON file! πŸ’βœ¨

RemoveCherryFromJson<Cherry>(777, "CherryBasket.json");

✨ This will remove the cherry with CherryId = 777 from CherryBasket.json! πŸ’–


πŸ’– Final Thoughts from Lucy Berry!

πŸŽ€ You did it, cuties! πŸŽ€ You’ve learned how to:
βœ… Use an interface (IHasCherryId) to make sure every cherry has an ID! πŸ’•
βœ… Read, parse, and remove data from JSON files without breaking the cuteness! πŸ’
βœ… Keep your code structured, safe, and super kawaii! 🌸✨


πŸ“ What’s Next?

πŸ’– Want to log every cherry removal? Add a cute logging function! πŸ’βœ¨
πŸ’– Need faster cherry processing? Use memory-mapped files for ultra speed! πŸš€
πŸ’– Thinking about saving cherries in a database? Try SQLite for super organization! πŸŽ€

πŸš€ Happy coding, cutie developers! πŸ’πŸ’– Lucy Berry loves you! πŸ’•πŸ’ž


⚠️ **GitHub.com Fallback** ⚠️