加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 18:40:35 所属栏目:百科 来源:网络整理
导读:我试图将一个简单的字符串序列化为BSON,但我不断得到这个错误; “写入字符串值时出错.BSON必须以对象或数组开头.路径” 我可以不使用Json.Net将’String’或简单类型序列化为BSON吗?如果不是为什么? 例如.; using (var ms = new MemoryStream()){ using (v
我试图将一个简单的字符串序列化为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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读