HandlingJson2 - lucyberryhub/WPF.Tutorial GitHub Wiki
๐ 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! ๐
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);
}
}
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! ๐
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);
}
}
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! ๐
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! ๐๐ท