JSON.NET cast error when serializing Mongo ObjectId

后端 未结 6 1244
旧巷少年郎
旧巷少年郎 2020-11-28 09:36

I am playing around with MongoDB and have an object with a mongodb ObjectId on it. When I serialise this with the .NET Json() method, all is good (but the dates are horrible

6条回答
  •  执念已碎
    2020-11-28 09:47

    I had a pointer from the MongoDB user group. https://groups.google.com/forum/?fromgroups=#!topic/mongodb-csharp/A_DXHuPscnQ

    The response was "This seems to be a Json.NET issue, but not really. There is a custom type here it simply doesn't know about. You need to tell Json.NET how to serialize an ObjectId."

    So, I implemented the following solution

    I decorated my ObjectId with

    [JsonConverter(typeof(ObjectIdConverter))]
    

    Then wrote a custom converter that just spits out the Guid portion of the ObjectId

     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)
        {
            throw new NotImplementedException();
        }
    
        public override bool CanConvert(Type objectType)
        {
            return typeof(ObjectId).IsAssignableFrom(objectType);
            //return true;
        }
    
    
    }
    

提交回复
热议问题