I decided to take I3arnon's advice and use Json.NET. The problem is Json.NET doesn't know how to handle most Mongo types, so serializing the Resume
property was problematic because it's of type BsonDocument
. Here's what I came up with:
Json.NET can normally serialize the result of a Mongo query, however the BsonDocument
gave it a problem. In the case of my example, Json.NET could not serialize Person
without special instructions on how to handle a BsonDocument
.
First, I created a JsonConverter
called BsonDocumentConverter:
public class BsonDocumentConverter : JsonConverter
{
public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object value, JsonSerializer serializer)
{
var settings = new JsonWriterSettings()
{
OutputMode = JsonOutputMode.Strict
};
writer.WriteRawValue(value.ToJson(settings));
}
public override object ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException("Why would I want to deserialize?");
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(BsonDocument);
}
}
This converter uses the MongoDB C# driver to serialize any BsonDocuments.
To use the converter:
var result = JsonConvert.SerializeObject(person, Formatting.None,
new JsonSerializerSettings() {
NullValueHandling = NullValueHandling.Ignore,
Converters = new List<JsonConverter>() {
new BsonDocumentConverter()
}
});
return Json(result, JsonRequestBehavior.AllowGet);