我试图将一个简单的字符串序列化为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.