How to format full results using the ToJson method in C#?

I’m using the C# Driver, at this point I’m using the ToJson method to convert the BsonDocument to text for output.

I like to use the built-in formatted output, so I tried using JsonWriterSettings and setting Indent=true:

var settings = new JsonWriterSettings(){ Indent = true } BsonDocument.ToJson(settings)

At present, the output result is still not completely formatted, only the outermost layer has indentation processing, and the data of array type is still not formatted for output. So I want to understand how to do full Json formatting using built-in functions.


Hi, @XzMitsui,

I tried to reproduce the behaviour with the following example:

using MongoDB.Bson;
using MongoDB.Bson.IO;

var bsonDocument = BsonDocument.Parse("{name: 'Alice', favouriteNumbers: [7,42,99], favouriteFruit: ['apple','orange','grapefruit','watermelon'], favouriteBook: { name: 'Stranger in a Strange Land', author: 'Robert A. Heinlein'}}");
var settings = new JsonWriterSettings { Indent = true };
var jsonOutput = bsonDocument.ToJson(settings);

This produced the following output:

  "name" : "Alice",
  "favouriteNumbers" : [7, 42, 99],
  "favouriteFruit" : ["apple", "orange", "grapefruit", "watermelon"],
  "favouriteBook" : {
    "name" : "Stranger in a Strange Land",
    "author" : "Robert A. Heinlein"

We observe that field names are quoted, arrays are formatted, and elements are indented correctly based on their nesting. Please provide a code example that does not produce the desired output so that we can better understand the problem.


Hi James,

Well,The json format output in your reply is the same as mine, but in fact the effect I want is this,where BeatInfo is an array.

    "_id" : ObjectId("60efc86036380bd6884acb92"), 
    "Name" : "李淳罡", 
    "ForceValue" : "99", 
    "NickName" : "青衫剑圣1234567", 
    "BeatInfo" : [

That is, data with composite types (such as arrays, inline documents, etc.) is indented thoroughly. can i do this?Thank you.


@James_Kovacs Forgot @ :smile:

The JsonWriter included in MongoDB.Bson does not indent arrays, only subdocuments. You would have to write your own CustomJsonWriter. Alternatively you could use the technique that I outlined and post-process the output to add new lines and indentation to array elements.