编辑
2025-09-25
C#
00

目录

摘要
正文
准备一个类
插入数据
更新数据
查询
全文搜索
替换

摘要

JsonFlatFileDataStore 是一个用于处理 JSON 文件数据的 C# 类,它提供了一种简单的方法来读取、写入和操作 JSON 数据。

正文

通过nuget安装包JsonFlatFileDataStore

image.png

准备一个类

C#
public class Person { public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } }

插入数据

image.png

C#
private async void btnInsert_Click(object sender, EventArgs e) { //打开一个数据库,如果不存在,将新建 var store = new DataStore("./data.json"); //取得一个学员集合 var collection = store.GetCollection<Person>(); //插入一个学员 var p1 = new Person() { Id = 1, Name = "Test", Age = 99 }; //插入一个学员 await collection.InsertOneAsync(p1); List<Person> ps = new List<Person> { new Person() { Id = 2, Name = "Test1", Age=110 }, new Person() { Id = 3, Name = "Test2", Age=120 }, new Person() { Id = 4, Name = "Test3", Age=130 } }; //批量插入 collection.InsertMany(ps); }

自动主键

C#
private void btnNextId_Click(object sender, EventArgs e) { var store = new DataStore("./data.json", keyProperty: "Id"); var collection = store.GetCollection("person"); collection.InsertOne(new Person { Name = "zs", Age = 19 }); //下一个Id var nextId = collection.GetNextIdValue(); collection.InsertOne(new Person { Name = "ls", Age = 29 }); }

更新数据

C#
private async void btnUpdate_Click(object sender, EventArgs e) { //打开一个数据库,如果不存在,将新建 var store = new DataStore("./data.json"); //取得一个学员集合 var collection = store.GetCollection<Person>(); var p1 = new Person() { Id = 1, Name = "Test", Age = 199 }; p1.Name = "John"; //通过Id更新数据 await collection.UpdateOneAsync(p1.Id, p1); }

image.png

查询

image.png

C#
private void btnSearch_Click(object sender, EventArgs e) { //打开一个数据库,如果不存在,将新建 var store = new DataStore("./data.json"); //取得一个学员集合 var collection = store.GetCollection<Person>(); var p1 = collection.AsQueryable().Where(x => x.Id == 1); txtJson.Text=System.Text.Json.JsonSerializer.Serialize(p1); }

全文搜索

C#
private void btnFullText_Click(object sender, EventArgs e) { var store = new DataStore("./data.json"); var collection = store.GetCollection("person"); //搜索带有test的属性的对像 var matches = collection.Find("test"); txtJson.Text = System.Text.Json.JsonSerializer.Serialize(matches); }

image.png

替换

C#
private void btnReplace_Click(object sender, EventArgs e) { var store = new DataStore("./data.json"); var collection = store.GetCollection("person"); var p1 = new Person() { Id = 99, Name = "Rick", Age = 20 }; //替换,找不到insert var ret = store.ReplaceItem("Person", p1); }

本文作者:技术老小子

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!