Last active
April 28, 2024 14:49
-
-
Save davideicardi/e001ce88663bb6ef1d9d04f96f8b16c6 to your computer and use it in GitHub Desktop.
BsonDocument to Json string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This method convert a json to a valid string json | |
// It should handle all mongodb data types correctly (Date, ObjectId, ...) thanks to the | |
// Newtonsoft.Json.Bson.BsonReader serializer | |
public string ToJson(BsonDocument bson) | |
{ | |
using (var stream = new MemoryStream()) | |
{ | |
using (var writer = new BsonBinaryWriter(stream)) | |
{ | |
BsonSerializer.Serialize(writer, typeof(BsonDocument), bson); | |
} | |
stream.Seek(0, SeekOrigin.Begin); | |
using (var reader = new Newtonsoft.Json.Bson.BsonReader(stream)) | |
{ | |
var sb = new StringBuilder(); | |
var sw = new StringWriter(sb); | |
using (var jWriter = new JsonTextWriter(sw)) | |
{ | |
jWriter.DateTimeZoneHandling = DateTimeZoneHandling.Utc; | |
jWriter.WriteToken(reader); | |
} | |
return sb.ToString(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
{"dvd":"sdfsd"}