4

I have a MVC .net project, and I am using mongodb. In some of my controller I return JsonResult with ObjectId. I want the ObjectId to be serialized as string. I found a similar problem and used this answer, using a custom JsonConverter : JSON.NET cast error when serializing Mongo ObjectId

However when i try to return a JsonResult (using return Json(myObject)) the JsonConverter is not called at all.

When i return a string using return JsonConvert.SerializeObject(myObject); the JsonConverter is reached and is successful.

What am I missing? Thanks!

1
  • Can you show some relevant code ? Commented Dec 3, 2014 at 8:25

1 Answer 1

4

Figured a solution, hope it will help someone. Basically in the controller instead of returning MVC's JsonResult, I returned the Newtonsoft's JObject.

My class looks like this:

using MongoDB.Bson;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
public class StubClass 
{
    [JsonConverter(typeof(ObjectIdConverter))]
    public ObjectId Id { get; set; }
}

The JsonConverter class looks like this:

using MongoDB.Bson;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

public class ObjectIdConverter : JsonConverter
{
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        serializer.Serialize(writer, value.ToString());

    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        JToken token = JToken.Load(reader);
        return new ObjectId(token.ToObject<string>());
    }

    public override bool CanConvert(Type objectType)
    {
        return typeof(ObjectId).IsAssignableFrom(objectType);
        //return true;
    }
}

And the controller:

using MongoDB.Bson;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
[HttpGet]
        public JObject Index()
        {
            StubClass c = new StubClass()
            {
                Id = ObjectId.GenerateNewId()
            };
            JObject jobj = JObject.FromObject(c);
            return jobj;
        }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.