0

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?

5
  • 2
    Modify your question to summarize what the link is doing. Don't make us go there to get the gist of what you're talking about. Commented Aug 10, 2016 at 18:38
  • BSON stands for Binary Structured Object Notation. Commented Aug 10, 2016 at 18:43
  • @MatiasCicero Not sure what you are trying to say? Commented Aug 10, 2016 at 18:44
  • So have you tried any other better way? Commented Aug 10, 2016 at 19:34
  • @VladimirNul I did what is in the answer accepted Commented Aug 10, 2016 at 19:36

1 Answer 1

4

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!

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.