简体   繁体   中英

Automatically retun mongodb ObjectId as string with Json.NET in MVC

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!

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;
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM