序列化 – 使用NewtonSoft Json.Net将简单字符串序列化为BSON时出错

我试图将一个简单的字符串序列化为BSON,但我不断得到这个错误;

“写入字符串值时出错.BSON必须以对象或数组开头.路径”

我可以不使用Json.Net将’String’或简单类型序列化为BSON吗?如果不是为什么?

例如.;

using (var ms = new MemoryStream())
{
    using (var bw = new BsonWriter(ms))
    {
        var serializer = new JsonSerializer();

        serializer.Serialize(bw,"Testing123");

        bw.Flush();
    }

    return ms.ToArray();
}

解决方法

来自bsonspec.org的 Quoted

BSON is a binary format in which zero or more key/value pairs are
stored as a single entity. We call this entity a document.

这意味着有效的BSON必须只能采用键/值对的形式,因此不可能将简单的值(如字符串或整数)写为BSON文档.

为什么数组可以作为完整的BSON文档通过,这里是引用来自Notes部分中相同来源的描述:

Array – The document for an array is a normal BSON document with
integer values for the keys,starting with 0 and continuing
sequentially. For example,the array ['red','blue'] would be encoded
as the document {'0': 'red','1': 'blue'}. The keys must be in ascending numerical order.

相关文章

文章浏览阅读2.4k次。最近要优化cesium里的热力图效果,浏览...
文章浏览阅读1.2w次,点赞3次,收藏19次。在 Python中读取 j...
文章浏览阅读1.4k次。首字母缩略词 API 代表应用程序编程接口...
文章浏览阅读802次,点赞10次,收藏10次。解决一个JSON反序列...
文章浏览阅读882次。Unity Json和Xml的序列化和反序列化_uni...