HandlingJson - lucyberryhub/WPF.Tutorial GitHub Wiki

πŸ’ Lucy Berry’s Magical Guide to JSON Files! ✨

Welcome to Lucy Berry’s Cherry Wonderland, where we store and retrieve data like a magical diary using JSON files! πŸ“–βœ¨ Let’s learn how to save, update, and delete data in the cutest way possible. πŸ“πŸ’–


πŸ’ What is a JSON File?

A JSON file is like a magical recipe book 🧁 where we store information in a structured way. Instead of writing things on paper, we save it digitally so that our cherry program can read, update, and delete entries easily! πŸ’–βœ¨


πŸ“ Step 1: Reading Data from a JSON File

Method Name: ReadBerryDataAsync<T>

(Reads the JSON file and gives you back a cute data list!)

We start by reading the file and turning the JSON data into a list of objects. πŸ’

public static async Task<T?> ReadBerryDataAsync<T>(string berryPath) where T : class
{
    if (!File.Exists(berryPath))
        return null; // πŸ’ If file doesn’t exist, return nothing!

    try
    {
        using (var stream = new FileStream(berryPath, FileMode.Open, FileAccess.Read, FileShare.Read))
        using (var reader = new StreamReader(stream, Encoding.UTF8))
        {
            string jsonData = await reader.ReadToEndAsync();
            return JsonConvert.DeserializeObject<T>(jsonData);
        }
    }
    catch (IOException ex)
    {
        System.Diagnostics.Debug.WriteLine($"πŸ“ Oops! Couldn’t read the berry file: {ex.Message}");
        return null;
    }
}

πŸ“ Example Usage:

var myBerries = await ReadBerryDataAsync<List<StrawberryData>>("berryBox.json");
if (myBerries != null)
{
    foreach (var berry in myBerries)
    {
        Console.WriteLine($"πŸ’ {berry.Name} is {berry.Color}!");
    }
}

πŸ’ Step 2: Deserializing Data from JSON

Method Name: DeserializeDataList<T>

(Takes JSON data and magically turns it into a list of berry objects! πŸ“βœ¨)

Now, we'll write a helper function to deserialize raw JSON data into objects. This is useful if we’re loading data manually (from a file or any string). πŸ“

public static List<T> DeserializeDataList<T>(string jsonData)
{
    try
    {
        if (string.IsNullOrWhiteSpace(jsonData))
            return new List<T>(); // πŸ’ If there’s no data, return an empty list.

        return JsonConvert.DeserializeObject<List<T>>(jsonData) ?? new List<T>();
    }
    catch (JsonException ex)
    {
        System.Diagnostics.Debug.WriteLine($"πŸ“ Oops! Couldn’t deserialize data: {ex.Message}");
        return new List<T>(); // πŸ’ If something went wrong, return an empty list!
    }
}

πŸ“ Example Usage:

string berryJsonData = File.ReadAllText("berryBox.json");
var berries = DeserializeDataList<StrawberryData>(berryJsonData);

foreach (var berry in berries)
{
    Console.WriteLine($"πŸ’ {berry.Name} is {berry.Color}!");
}

πŸ’ Step 3: Adding or Updating Data in JSON

Method Name: AddOrUpdateBerry<T>

(If the berry exists, update it! If it doesn’t, add a fresh berry! πŸ“βœ¨)

When you want to add or update a berry, you can use this method. It will check if the berry already exists. If it does, we update it; if it doesn’t, we add it to the list. πŸ’

public static async Task AddOrUpdateBerry<T>(string berryPath, Func<T, bool> matchBerry, T newBerry) where T : class
{
    var berryList = await ReadBerryDataAsync<List<T>>(berryPath) ?? new List<T>();

    var existingBerry = berryList.FirstOrDefault(matchBerry);
    if (existingBerry != null)
    {
        var index = berryList.IndexOf(existingBerry);
        berryList[index] = newBerry;
    }
    else
    {
        berryList.Add(newBerry);
    }

    await SaveBerryDataAsync(berryPath, berryList);
}

πŸ“ Example Usage:

await AddOrUpdateBerry(
    "berryBox.json",
    berry => berry.Id == 1,
    new StrawberryData { Id = 1, Name = "Sweet Cherry", Color = "Red" }
);

πŸ’ Step 4: Saving Data to a JSON File

Method Name: SaveBerryDataAsync<T>

(Writes data into a JSON file like a diary entry! πŸ“πŸ“–βœ¨)

Once the list of berries has been updated, we need to save it back to the JSON file. This method will serialize the list and write it to the file. πŸ’βœ¨

public static async Task SaveBerryDataAsync<T>(string berryPath, T data)
{
    if (data == null) return;

    try
    {
        string jsonData = JsonConvert.SerializeObject(data, Formatting.Indented);

        using (var stream = new FileStream(berryPath, FileMode.Create, FileAccess.Write, FileShare.None))
        using (var writer = new StreamWriter(stream, Encoding.UTF8))
        {
            await writer.WriteAsync(jsonData);
        }
    }
    catch (IOException ex)
    {
        System.Diagnostics.Debug.WriteLine($"πŸ“ Oops! Couldn’t write to berry file: {ex.Message}");
    }
}

πŸ“ Example Usage:

var berries = new List<StrawberryData>
{
    new StrawberryData { Id = 1, Name = "Berry Queen", Color = "Pink" }
};

await SaveBerryDataAsync("berryBox.json", berries);

πŸ’ Step 5: Removing a Berry from JSON

Method Name: RemoveBerry<T>

(Deletes a berry from the JSON file if it’s already there! πŸ“πŸ’”)

Sometimes, we need to remove a berry. This method finds the berry and deletes it from the list, saving the updated list afterward. πŸ’

public static void RemoveBerry<T>(long berryId, string berryPath) where T : class, IHasId
{
    if (string.IsNullOrWhiteSpace(berryPath) || !File.Exists(berryPath))
        return;

    try
    {
        List<T> berryList;

        using (var reader = new StreamReader(berryPath))
        {
            string jsonData = reader.ReadToEnd();
            if (string.IsNullOrWhiteSpace(jsonData)) return;

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

        var berryToRemove = berryList.FirstOrDefault(x => x.Id == berryId);
        if (berryToRemove != null)
        {
            berryList.Remove(berryToRemove);

            using (var writer = new StreamWriter(berryPath, false, Encoding.UTF8))
            {
                writer.Write(JsonConvert.SerializeObject(berryList, Formatting.Indented));
            }
        }
    }
    catch (JsonException ex)
    {
        throw new InvalidOperationException($"πŸ“ Couldn’t read or parse berry file: {berryPath}", ex);
    }
    catch (IOException ex)
    {
        throw new InvalidOperationException($"πŸ“ File access error: {berryPath}", ex);
    }
}

πŸ“ Example Usage:

RemoveBerry<StrawberryData>(1, "berryBox.json");

πŸ“ Summary Table for Quick Reference!

πŸ’ Lucy Berry Method πŸ“– What It Does?
ReadBerryDataAsync<T> Reads data from a JSON file πŸ“
DeserializeDataList<T> Converts raw JSON data into a list of berry objects πŸ“βœ¨
AddOrUpdateBerry<T> Updates an existing berry or adds a new one πŸ’βœ¨
SaveBerryDataAsync<T> Writes data to a JSON file πŸ“–βœ¨
RemoveBerry<T> Removes a berry from the JSON file πŸ’”πŸ“

πŸŽ€ Final Thoughts from Lucy Berry! πŸ’βœ¨

Now you can store and manage all your magical cherry data in JSON files! πŸ“πŸ’• Whether it’s reading, updating, or deleting, you have a cute and easy way to keep everything organized! πŸŽ€βœ¨

Happy coding in Berry Wonderland! πŸ’ Keep being adorable and magical! πŸ’–βœ¨


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