Book Image

JavaScript JSON Cookbook

By : Ray Rischpater, Brian Ritchie, Ray Rischpater
Book Image

JavaScript JSON Cookbook

By: Ray Rischpater, Brian Ritchie, Ray Rischpater

Overview of this book

Table of Contents (17 chapters)
JavaScript JSON Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Decoding data from BSON using Json.NET


Using Json.NET, decoding BSON is the opposite of encoding; given a class that describes the data to decode and a blob of binary data, invoke a reader to read the data.

Getting ready

Of course, you need a reference to the Json.NET assembly in your project in order to do this. See recipe How to Deserialize an object using Json.NET in Chapter 7, Using JSON in a Type-safe Manner, to learn how to add a reference to Json.NET in your application using NuGet.

How to do it…

Starting with a stream, you'll use a BsonReader with a JsonSerializer to deserialize the BSON. Assuming data is byte[] of BSON data:

MemoryStream ms = new MemoryStream(data);
using (var reader = new Newtonsoft.Json.Bson.BsonReader(ms))
{
  var serializer = new Newtonsoft.Json.JsonSerializer();
  var r = serializer.Deserialize<Record>(reader);

  // use r
}

How it works…

We create MemoryStream from the incoming data, which we use with BsonReader to actually read the data from the stream. The...