Maxime Joyal
Maxime Joyal

Reputation: 183

How to use a string instead of a stream?

I need to use this:

http://www.newtonsoft.com/json/help/html/SerializeToBson.htm

This is code to convert object to BSON format. The code which interests me is this:

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);
}

However, I want the result in a string. So do I really have to use a stream or a file to write stuff in, then read it to put it in the string?

There must be a better way to do this?

Upvotes: 0

Views: 219

Answers (1)

Matías Fidemraizer
Matías Fidemraizer

Reputation: 64923

You can get the string from the stream using 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();
        }

Or also, 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());
        }

BTW who knows what you're going to get from this, since BSON is a binary object representation, it's not like JSON!

Upvotes: 4

Related Questions