介绍
在VS2022控制台项目中,通过NuGet安装Newtonsoft.Json.Bson1.0.3:

该库用来读写bson格式的文件,也就是json文件的二进制版本的文件。
示例
简单封装的BsonUtil工具类
csharp
using Newtonsoft.Json;
using Newtonsoft.Json.Bson;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
namespace Util
{
public class BsonUtil
{
public static bool Read<T>(string bsonPath, out T t)
{
t = default;
if (!File.Exists(bsonPath))
{
return false;
}
try
{
var bytes = File.ReadAllBytes(bsonPath);
MemoryStream ms = new MemoryStream(bytes);
using (BsonReader reader = new BsonReader(ms))
{
JsonSerializer serializer = new JsonSerializer();
try
{
t = serializer.Deserialize<T>(reader);
return true;
}
catch (Exception e)
{
t = default;
return false;
}
}
}
catch (System.Exception e)
{
t = default;
return false;
}
}
public static void Save(string fileFullPath, object obj)
{
MemoryStream ms = new MemoryStream();
using (BsonWriter writer = new BsonWriter(ms))
{
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(writer, obj);
}
File.WriteAllBytes(fileFullPath, ms.ToArray());
}
}
}
调用示例
先是将一个实体类存储为bson文件,再将其读取进来,可以打断点查看读进来的属性。
csharp
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
namespace Demos{
public class BsonDemos
{
public class Building
{
public List<Layer> layers = new List<Layer>();
}
public class Layer
{
public string name;
public bool visible;
public List<Entity> entities = new List<Entity>();
}
public class Entity
{
public int id;
public string type;
}
public static void Test()
{
var bui = new Building();
var layer = new Layer() { name = "0" };
layer.entities.Add(new Entity { id = 1, type = "LINE" });
layer.entities.Add(new Entity { id = 2, type = "CIRCLE" });
layer.entities.Add(new Entity { id = 3, type = "ARC" });
bui.layers.Add(layer);
layer = new Layer() { name = "1" };
layer.entities.Add(new Entity { id = 4, type = "POLYLINE" });
layer.entities.Add(new Entity { id = 5, type = "INSERT" });
layer.entities.Add(new Entity { id = 6, type = "POINT" });
bui.layers.Add(layer);
var path = "./bui.d";
BsonUtil.Save(path, bui);
if (BsonUtil.Read(path, out Building bui2))
{
//成功创建
}
if (BsonUtil.Read(path, out JContainer j))
{
var layers = j["layers"];
var layer1 = layers[0];
var layer1Name = layer1["name"].ToString();
//to do
}
}
}
}