This article will demonstrate how to implement CRUD functionality with JSON file in a project using C# code. This article gives you an idea how you can perform CRUD operations on JSON files and use JSON files as a database.
the classes
the classes
namespace Miniblog.Core.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Text;
using System.Text.RegularExpressions;
public class Post
{
public IList<string> Categories { get; } = new List<string>();
public IList<string> Tags { get; } = new List<string>();
public IList<Comment> Comments { get; } = new List<Comment>();
[Required]
public string Content { get; set; } = string.Empty;
step 2:using System.Text.Json to save the file system(not Newtonsoft.Json)
using System.Text.Json;
Step 3: create FileBlogJsonDataService.cs to implement CRUD interface IBlogService
Serialize and save
public class FileBlogJsonDataService : IBlogService
public async Task SavePost(Post post)
{
if (post is null)
{
throw new ArgumentNullException(nameof(post));
}
var filePath = this.GetFilePath(post);
post.LastModified = DateTime.UtcNow;
// Serialize and save
var serializedData = JsonSerializer.Serialize(post);
await File.WriteAllTextAsync(filePath, serializedData);
if (!this.cache.Contains(post))
{
this.cache.Add(post);
this.SortCache();
}
}
Read and deserialize
private void LoadPosts()
{
if (!Directory.Exists(this.folder))
{
Directory.CreateDirectory(this.folder);
}
// Can this be done in parallel to speed it up?
foreach (var file in Directory.EnumerateFiles(this.folder, "*.json", SearchOption.TopDirectoryOnly))
{
// Read and deserialize
var rawData = File.ReadAllText(file);
var post = JsonSerializer.Deserialize<Post>(rawData);
//LoadCategories(post, doc);
//LoadComments(post, doc);
this.cache.Add(post);
}
}
Step 4:
program.cs
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
//new
builder.Services.AddSingleton<IBlogService, FileBlogJsonDataService>();
var app = builder.Build();
Useful links