HandlingJson - lucyberryhub/WPF.Tutorial GitHub Wiki
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. ππ
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! πβ¨
(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;
}
}
var myBerries = await ReadBerryDataAsync<List<StrawberryData>>("berryBox.json");
if (myBerries != null)
{
foreach (var berry in myBerries)
{
Console.WriteLine($"π {berry.Name} is {berry.Color}!");
}
}
(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!
}
}
string berryJsonData = File.ReadAllText("berryBox.json");
var berries = DeserializeDataList<StrawberryData>(berryJsonData);
foreach (var berry in berries)
{
Console.WriteLine($"π {berry.Name} is {berry.Color}!");
}
(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);
}
await AddOrUpdateBerry(
"berryBox.json",
berry => berry.Id == 1,
new StrawberryData { Id = 1, Name = "Sweet Cherry", Color = "Red" }
);
(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}");
}
}
var berries = new List<StrawberryData>
{
new StrawberryData { Id = 1, Name = "Berry Queen", Color = "Pink" }
};
await SaveBerryDataAsync("berryBox.json", berries);
(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);
}
}
RemoveBerry<StrawberryData>(1, "berryBox.json");
π 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 ππ |
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! πβ¨