JsonFlatFileDataStore
是一个用于处理 JSON 文件数据的 C# 类,它提供了一种简单的方法来读取、写入和操作 JSON 数据。
通过nuget安装包JsonFlatFileDataStore
C#public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
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);
}
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);
}
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 许可协议。转载请注明出处!