I decided to take I3arnon advice and use Json.NET. The problem is that Json.NET does not know how to handle most types of Mongo, so serializing the Resume property was problematic because it is a BsonDocument type. Here is what I came up with:
Json.NET can usually serialize the result of a Mongo request, however BsonDocument gave it a problem. In the case of my example, Json.NET was unable to serialize Person without special instructions on how to handle 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);
source share