我需要使用这个:
http://www.newtonsoft.com/json/help/html/SerializeToBson.htm这是将对象转换为BSON格式的代码。我感兴趣的代码是:
System.IO.MemoryStream stream = new System.IO.MemoryStream();
using (Newtonsoft.Json.Bson.BsonWriter writer = new Newtonsoft.Json.Bson.BsonWriter(stream))
{
Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();
serializer.Serialize(writer, message);
}
但是,我希望结果是字符串。那么,我真的必须使用流或文件来写入内容,然后读取它以将其放入字符串中吗?
一定有更好的方法来做这件事吗?
您可以使用StreamReader.ReadToEnd()
:
string bsonText = "";
using(MemoryStream stream = new MemoryStream())
using(StreamReader reader = new StreamReader(stream))
using (BsonWriter writer = new Newtonsoft.Json.Bson.BsonWriter(stream))
{
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(writer, message);
stream.Position = 0;
bsonText = reader.ReadToEnd();
}
或者,Encoding.UTF8.GetString()
:
using(MemoryStream stream = new MemoryStream())
using (BsonWriter writer = new Newtonsoft.Json.Bson.BsonWriter(stream))
{
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(writer, message);
bsonText = Encoding.UTF8.GetString(stream.ToArray());
}
谁知道你会从这里得到什么,因为BSON是一个二进制对象表示,它不像JSON!