Skip to content

Instantly share code, notes, and snippets.

@cleydson
Created June 7, 2016 17:59
Show Gist options
  • Save cleydson/d1583f87f6fb7e2a8ee67e2455a1bb56 to your computer and use it in GitHub Desktop.
Save cleydson/d1583f87f6fb7e2a8ee67e2455a1bb56 to your computer and use it in GitHub Desktop.
MongoDB:: Converter ObjectId to json, so you can use the attribute [JsonProperty("_id"), JsonConverter(typeof(ObjectIdConverter))] over your property.
using MongoDB.Bson;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
namespace Your.Namespace
{
public class ObjectIdConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if(value.GetType().IsArray)
{
writer.WriteStartArray();
foreach (var item in (Array)value)
{
serializer.Serialize(writer, item);
}
writer.WriteEndArray();
}
else
serializer.Serialize(writer, value.ToString());
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var token = JToken.Load(reader);
var objectIds = new List<ObjectId>();
if (token.Type == JTokenType.Array)
{
foreach (var item in token.ToObject<string[]>())
{
objectIds.Add(new ObjectId(item));
}
return objectIds.ToArray();
}
if (token.ToObject<string>().Equals("MongoDB.Bson.ObjectId[]"))
{
return objectIds.ToArray();
}
else
return new ObjectId(token.ToObject<string>());
}
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(ObjectId));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment